开发者

Does the BackgroundWorker provide real multithreading?

开发者 https://www.devze.com 2022-12-20 05:57 出处:网络
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:

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 s开发者_如何学Cuch 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消