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?
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();
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.
If you create many BackgroundWorker
instances then you get many threads, a single instance provides for only a single background task however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With