I have a method Foo()
, which creates and runs a BackgroundWorker
.
RunWorkerCompleted
, ProgressChanged
etc. are handled inside Foo()
.
My main thread calls MyObject.Foo()
.
Right after calling MyObject.Foo()
main thread calls MyObject.DoSthWithFooData()
.
Main Thread doesn't know anything about the BackgroundWorker
inside MyObject.Foo()
.
How can I force main thread to wait until BackgroundWorker
has finished its work?
DoSthWithFooData()
must be called when the BackgroundWorker
in MyObject.Foo()
has finished its job.
You don't want the main thread to wait for the BackgroundWorker. That would cause your GUI to become unresponsive - not a good user experience. The whole point of using the BackgroundWorker in the first place is to avoid blocking the main thread. Instead you should register an event handler for the background worker's RunWorkerCompleted
event. The code in the event handler will be run when the background task completes.
If you want to prevent users from interacting with the program while the background task is running then:
RunWorkerCompleted
event handler. 将DoSthWithFooData
放入RunWorkerCompleted
事件中
You have two choices:
BackgroundWorker
entirely and just execute your code synchronously. If you're going to force the code to wait on the BackgroundWorker
to finish anyway, then that's essentially what you're doing. This is not the best option, assuming that the next is practical for you. MyObject.Foo()
into the RunWorkerCompleted
event handler. This is preferred, as it will maintain the "background" element of the work and the UI will remain responsive. Give Foo() a parameter a callbacb Action delegate that is called when foo is done And then you can Use MenualResetEvent to wait for Foo to finish.
when Action delegate is called signal ManualReset event
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.