通过BackgroundWorker的募集活动预期线程不执行线程、BackgroundWorker

2023-09-04 00:50:31 作者:是男人就像爷们一样

一个WinForms对话框使用BackgroundWorker的与显著成功执行一些异步操作。有时,异步进程正由后台工作运行将需要提高事件的WinForms应用程序的用户响应(消息,询问用户是否希望取消),响应其捕获到事件的CancelEventArgs类型。

A winforms dialog is using BackgroundWorker to perform some asynchronous operations with significant success. On occasion, the async process being run by the background worker will need to raise events to the winforms app for user response (a message that asks the user if they wish to cancel), the response of which captured in an CancelEventArgs type of the event.

作为线程的实现,我本来期望工人的的RaiseEvent火,然后工人将继续,因此需要我暂停工人,直到接收到响应。然而相反,在工作人员保持等待的加薪事件中执行完成code。

Being an implementation of threading, I would have expected the RaiseEvent of the worker to fire, and then the worker would continue, hence requiring me to pause the worker until the response is received. Instead however, the worker is held to wait for the code executed by the raise event to complete.

好像方法,我呼吁通过事件调用实际上是由后台工作人员的工作线程上,我觉得很奇怪,因为我希望看到它的主线程这哪里是MainForm的运行。而且奇怪的是,有没有抛出跨线程异常。

It seems like method I am calling via the event call is actually on the worker thread used by the background worker, and I am surprised, since I expected to see it on the Main Thread which is where the mainform is running. Also surprisingly, there are no cross thread exceptions thrown.

能否有人请解释为什么这是不是如我所料?

Can somebody please explain why this is not as I expect?

推荐答案

BackgroundWorker的将提高其 ProgressChanged 事件和 UI线程RunWorkerCompleted 事件(更准确的说,它会发布他们利用当前建立的SynchronizationContext线程。)

The BackgroundWorker will raise its ProgressChanged event and RunWorkerCompleted event on the UI thread (more accurately, it will post them to the thread using the currently established SynchronizationContext.)

但是,这不只是使您能够提高UI线程上的任意事件。对于您要访问的SynchronizationContext.Current并使用帖子方法。

But it will not simply enable you to raise arbitrary events on the UI thread. For that you should access the SynchronizationContext.Current and use the Post method.

 
精彩推荐
图片推荐