which thread does backgroundworker completed event

2020-08-17 07:26发布

问题:

I have a GUI application that needs to run long calculations (think a minute or more) and the way that it deals with this is by giving the calculation to a background worker. (this part is fine)

The question I have is if I do something like: this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.doSomethingElse);

is doSomethingElse going to be run on the main UI thread or whatever in the thread pool the background worker ran on?

thank for any help you can provide.

回答1:

It's going to be run in the same thread that BackgroundWorker is in, ie most usually the UI thread.



回答2:

is doSomethingElse going to be run on the main UI thread

Yes, that is the main reason of being for a Backgroundworker. It has 3 events, only DoWork will be executed on a separate (ThreadPool) thread. Completed and ProgressChanged will be marshaled to the 'main' thread.



回答3:

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.

See this post and this connect issue for more information.

https://stackoverflow.com/a/2806824/279999

http://connect.microsoft.com/VisualStudio/feedback/details/116930/backgroundworker-components-progresschanged-and-runworkercompleted-event-run-on-wrong-thread