views:

374

answers:

3

Learning to build multithreading WPF applications I read about some restrictions in using BackgroundWorker that was not very clear for me. Please, help me to understand:

If I want not only one thread working behind the scene of UI, but maybe several ones, starting and ending independently one from another, will the BackgroundWorker fit in such a case? Can I have multiple instances of the BackgroundWorker?

Simply put, does the BackgroundWorker provide a multithreading and not simply a two-threading?

+8  A: 

Each BackgroundWorker runs a on a separate thread. You can create as many background workers as you need to run operations in parallel, so in that sense it is true multithreading.

The benefit of BackgroundWorker is the ease with which you can subscribe events that will fire on your UI thread when the time-consuming task completes.

Using BackgroundWorker is actually quite simple:

var worker1 = new System.ComponentModel.BackgroundWorker();
worker1.DoWork += (sender,e) => Thread.Sleep(10000);
worker1.RunWorkerCompleted += (sender,e) => MessageBox.Show("Worker1 Finished!");
worker1.RunWorkerAsync();
LBushkin
+1  A: 

If you create many BackgroundWorker instances then you get many threads, a single instance provides for only a single background task however.

Pent Ploompuu
A: 

Yes, internally, the Background worker calls BeginInvoke on you're provided delegate. This will result in your delegate being placed on a thread pool in the CLR.

Steve Sheldon