我怎样才能等待BackgroundWorker?
我有一个方法 Foo()
,它创建并运行一个 BackgroundWorker
。RunWorkerCompleted
、ProgressChanged
等在 Foo()
内部处理。
我的主线程调用 MyObject.Foo()
。
在调用 MyObject.Foo()
之后,主线程立即调用 MyObject.DoSthWithFooData()
。
主线程对 MyObject.Foo()
内的 BackgroundWorker
一无所知。
如何强制主线程等待 BackgroundWorker
完成其工作?
当 MyObject.Foo()
中的 BackgroundWorker
完成其工作时,必须调用 DoSthWithFooData()
。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不希望主线程等待BackgroundWorker。这会导致你的 GUI 变得无响应——这不是一个好的用户体验。首先使用BackgroundWorker 的全部目的是避免阻塞主线程。相反,您应该为后台工作人员的
RunWorkerCompleted
事件。事件处理程序中的代码将在后台任务完成时运行。如果您想阻止用户在后台任务运行时与程序交互,那么:
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
事件中put the
DoSthWithFooData
in theRunWorkerCompleted
Event您有两种选择:
BackgroundWorker
并仅同步执行您的代码。如果您要强制代码等待BackgroundWorker
完成,那么这实际上就是您正在做的事情。这不是最好的选择,假设下一个对您来说是实用的。MyObject.Foo()
后的逻辑移至RunWorkerCompleted
事件处理程序中。这是首选,因为它将保留作品的“背景”元素,并且 UI 将保持响应。You have two choices:
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.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.为 Foo() 提供一个参数,当 foo 完成时调用的 callbacb 操作委托
然后您可以使用 MenualResetEvent 等待 Foo 完成。
当 Action delegate 被调用时发出 ManualReset 事件信号
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