Search code examples
vb.netbackgroundworker

How to dynamically create a background worker in VB.net


I have a VB.net project which uses a background worker to do some stuff.

Now I want to expand the project to be able to do multiple stuff :)

A user can enter an URL in a textbox and when the user click on the parse button the program creates a new tabcontrol a outputs some data.

I use a hardcoded background worker for this.

But now I want to run multiple background workers to do this stuff so I can't rely on hard coding the background worker(s).

Is it possible to create background workers dynamically.

I just don't have any idea how to set this up since I think I need to set up the different methods and variables like:

Private bw As BackgroundWorker = New BackgroundWorker
bw.WorkerReportsProgress = True
bw.WorkerSupportsCancellation = True
AddHandler bw.DoWork, AddressOf bw_DoWork
AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
bw.RunWorkerAsync()

Private Sub bw_DoWork(), Private Sub bw_RunWorkerCompleted() and Private Sub bw_ProgressChanged()

I think I need to declare the background workers in some sort of array like variable (list / dictionary)??? Other then that I have no idea how to tackle this.


Solution

  • Although BackgroundWorkers can be the best, simplest, and smartest way to multithread sometimes, I think you might now look to use one of the other ways to multithread.

    There are lots of debates/arguments/trolling regarding which methods are the best to use in each circumstance, so my advice to you would be to have a quick look at the following articles and decide for yourself (or if you can't find good enough resources to make a decision, ask on SO of course).

    You've obviously looked at back ground workers already so I won't list them, nor will I list all the ways you can thread, just a couple that might be of interest to you.

    First off, check out the ThreadPool. It's easy to use, and it makes fairly good use of recycling/re-using resources. There are some cons such as using/holding too many threads from a pool can exhuast the pool, but in simple applications that shouldn't be an issue.

    There is also the CLR Async model which is supported across a suprising amount of the framework itself, particularly in cases involving some form of IO resource (file, network, etc).

    Another approach is the Parallel Class which is one of my favourites - I've been hooked on multiline lambda since it was introduced and parallel provides a good platform for doing so.

    In all of the above cases, you can create tertiary threads on the fly, without having to create and maintain a pool of background workers yourself. It's hard to say which approach would work best for you from the information provided, but personally, I'd consider the threadpool if retrieval of the data to populate your tabs doesn't take too long.

    Hope that helps!