简体   繁体   English

WPF中的BackgroundWorker和Dispatcher.BeginInvoke

[英]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? 任何人都可以在WPF中告诉我为什么我们可以通过在DoWork事件Eventhandler中调用ReportProgress()方法使用ProgressChangedEvent事件处理程序更新UI时,为什么需要使用Dispatcher.BeginInvoke()方法从DoworkEvent处理程序中更新UI? 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. 需要从UI线程完成UI的更新。

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. 分派器分派器是一个对象,当您调用BeginInvoke时,它将在创建分派器的线程上执行该方法。 The Application's dispatcher is always created on the UI thread, hence this will work. 应用程序的调度程序始终在UI线程上创建,因此可以正常工作。

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. 后台工作程序后台工作程序非常相似,尽管它提供了基于事件的API:当您在DoWork方法中调用ReportProgress ,BackgroundWorker将在创建后台工作程序的线程上引发一个事件。 So if you create the Background-Worker on the UI thread, you can update the UI inside the ProgressChanged event handler. 因此,如果在UI线程上创建Background-Worker,则可以在ProgressChanged事件处理程序中更新UI。

You can safely update the UI from a BackgroundWorker's ProgressChanged handler without any need for calling the Dispatcher. 您可以从BackgroundWorker的ProgressChanged处理程序安全地更新UI,而无需调用Dispatcher。

The ProgressChanged event will by raised whenever you call ReportProgress . 每当您致电ReportProgress时,都会引发ProgressChanged事件。 It is executed on the thread that created the BackgroundWorker instance, which is usually the UI thread. 它在创建BackgroundWorker实例的线程上执行,该实例通常是UI线程。

From the Remarks section in ReportProgress: 在ReportProgress的“备注”部分中:

The call to the ReportProgress method is asynchronous and returns immediately. 对ReportProgress方法的调用是异步的,并立即返回。 The ProgressChanged event handler executes on the thread that created the BackgroundWorker. ProgressChanged事件处理程序在创建BackgroundWorker的线程上执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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