简体   繁体   中英

BackgroundWorker RunWorkerCompleted Event

My C# application has several background workers. Sometimes one background worker will fire off another. When the first background worker completes and the RunWorkerCompleted event is fired, on which thread will that event fire, the UI or the first background worker from which RunWorkerAsync was called? I am using Microsoft Visual C# 2008 Express Edition. Any thoughts or suggestions you may have would be appreciated. Thanks.

If the BackgroundWorker was created from the UI thread, then the RunWorkerCompleted event will also be raised on the UI thread.

If it was created from a background thread, the event will be raised on an undefined background thread (not necessarily the same thread, unless you're using a custom SynchronizationContext ).

Interestingly, this doesn't seem to be all that well-documented on MSDN. The best reference I was able to find was here :

The preferred way to implement multithreading in your application is to use the BackgroundWorker component. The BackgroundWorker component uses an event-driven model for multithreading. The background thread runs your DoWork event handler, and the thread that creates your controls runs your ProgressChanged and RunWorkerCompleted event handlers. You can call your controls from your ProgressChanged and RunWorkerCompleted event handlers.

根据我的观察,RunWorkerCompleted 是在调用 RunWorkerAsync 的线程上执行的,它不一定是创建后台工作线程的线程。

On same issue found this thread msdn . In short insert

AsyncOperationManager.SynchronizationContext = new DispatcherSynchronizationContext(this.Dispatcher)

before RunWorkerAsync call.

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