简体   繁体   中英

BackgroundWorker and Dispatcher.BeginInvoke in WPF

Can anyone tell me in WPF why we need to use Dispatcher.BeginInvoke() method to update UI from DoworkEvent handler when we can update UI using ProgressChangedEvent event handler by calling ReportProgress() method in DoWork event Eventhandler? Correct me if my understanding about Background worker and dispatcher are incorrect?

There's one rule you need to remember:

Updating the UI needs to be done from the UI thread.

Keeping this in mind, let's see what the dispatcher does and what the backgroundworker does:

Dispatcher The dispatcher is an object that, when you call BeginInvoke, will execute the method on the thread the dispatcher was created. The Application's dispatcher is always created on the UI thread, hence this will work.

Background worker The background worker is very similar, although it offers an event-based API: When you call ReportProgress inside the DoWork-method, the BackgroundWorker will raise an event on the thread the background-worker was created. So if you create the Background-Worker on the UI thread, you can update the UI inside the ProgressChanged event handler.

You can safely update the UI from a BackgroundWorker's ProgressChanged handler without any need for calling the Dispatcher.

The ProgressChanged event will by raised whenever you call ReportProgress . It is executed on the thread that created the BackgroundWorker instance, which is usually the UI thread.

From the Remarks section in ReportProgress:

The call to the ReportProgress method is asynchronous and returns immediately. The ProgressChanged event handler executes on the thread that created the BackgroundWorker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM