How can I wait for BackgroundWorker?
I have a method Foo()
, which creates and runs a BackgroundWorker
.
RunWorkerCompleted
, Progr开发者_JS百科essChanged
etc. are handled inside Foo()
.
My main thread calls MyObject.Foo()
.
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:
- Disable the relevant controls when you start the BackgroundWorker.
- Re-enable them again in the
RunWorkerCompleted
event handler.
put the DoSthWithFooData
in the RunWorkerCompleted
Event
You have two choices:
- You can remove the
BackgroundWorker
entirely and just execute your code synchronously. If you're going to force the code to wait on theBackgroundWorker
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. - Move the logic that would ordinarily follow the call to
MyObject.Foo()
into theRunWorkerCompleted
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
精彩评论