为什么没有一个BackgroundWorker需要在ProgressChanged事件处理程序调用? [英] Why doesn't a BackgroundWorker need Invoke in the ProgressChanged event handler?

查看:358
本文介绍了为什么没有一个BackgroundWorker需要在ProgressChanged事件处理程序调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 ProgressChanged 事件处理程序是从什么地方了的DoWork 事件处理程序中提出,不应该他们被称为而不是在UI线程异步操作线程,的DoWork 也运行上,因此需要调用或的BeginInvoke 操纵控制?

Since the ProgressChanged event handler is raised from somewhere within the DoWork event handlers, shouldn't they be called on the asynchronous operation thread, which DoWork also runs on, instead of the UI thread, and therefore require Invoke or BeginInvoke to manipulate controls?

我的猜测是,一些神奇正在发生的事情 ReportProgress 方法中,但它是如何知道哪一个才是正确的线程调用 ProgressChanged 事件处理程序?

My guess is that some magic is happening within the ReportProgress method, but how does it even know, which one is the correct thread to invoke the ProgressChanged event handlers on?

推荐答案

当你调用的RunWorkerAsync 的BackgroundWorker 在内部创建一个新的 的AsyncOperation 与当前同步上下文相关联,如通过<一个检索href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperationmanager.synchronizationcontext.aspx"相对=nofollow> AsyncOperationManager.SynchronizationContext 的静态属性。

When you call RunWorkerAsync, the BackgroundWorker internally creates a new AsyncOperation associated with the current synchronization context, as retrieved through the AsyncOperationManager.SynchronizationContext static property.

此同步上下文将是一个派生类的一个实例从 的SynchronizationContext 。具体类型取决于同步模型提供应用程序使用。如果您运行的是Windows窗体,这将是<一href="http://msdn.microsoft.com/en-us/library/system.windows.forms.windowsformssynchronizationcontext"相对=nofollow> WindowsFormsSynchronizationContext ; WPF的;这将是<一href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchersynchronizationcontext"相对=nofollow> DispatcherSynchronizationContext

This synchronization context would be an instance of a class deriving from SynchronizationContext. The specific type depends on the synchronization model provider your application uses. If you’re running Windows Forms, it would be WindowsFormsSynchronizationContext; on WPF; it would be DispatcherSynchronizationContext.

在随后调用 ReportProgress 的后台线程,的BackgroundWorker 将在内部调用的 发布 在上述的SynchronizationContext 实例,从而调度操作异步相关线程。

When you subsequently call ReportProgress on the background thread, the BackgroundWorker would internally call Post on the aforementioned SynchronizationContext instance, thereby dispatching the operation to the associated thread asynchronously.

在Windows窗体,这是作为一个的 Control.BeginInvoke 调用;在WPF中,它成为一个 调度.BeginInvoke 电话。

In Windows Forms, this is implemented as a Control.BeginInvoke call; on WPF, it becomes a Dispatcher.BeginInvoke call.

这篇关于为什么没有一个BackgroundWorker需要在ProgressChanged事件处理程序调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆