Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the BackgroundWorker provide real multithreading?

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?

like image 871
rem Avatar asked Feb 13 '10 13:02

rem


3 Answers

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();
like image 153
LBushkin Avatar answered Nov 16 '22 16:11

LBushkin


The restrictions you quote (from Pro WPF) stem from the fact that a BGW uses the ThreadPool so all rules and adivice regarding ThreadPool threads do apply.

like image 31
Henk Holterman Avatar answered Nov 16 '22 16:11

Henk Holterman


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

like image 2
Pent Ploompuu Avatar answered Nov 16 '22 16:11

Pent Ploompuu