等待BackgroundWorker RunWorkerCompleted
在主线程中,我有一个计时器。在 Tick
事件中,我运行一个 BackgroundWorker
。我在那里做了一些事情,然后 BackgroundWorker
调用 RunWorkerCompleted
事件。
在主线程中,我有函数 Stop
。此函数禁用定时器
。但我想在 BackgroundWorker
工作时等待他。
例如:
public void Next()
{
// Start the asynchronous operation
if (!this._backgroundWorker.IsBusy)
this._backgroundWorker.RunWorkerAsync();
}
private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
DoSomething();
}
private void _backgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
DoSomethingElse();
}
public void Stop()
{
this._timer.Enabled = false;
}
所以我的问题是如何等待BackgroundWorker
的RunWorkerCompleted
事件?我需要等到 DoSomethingElse();
完成。
谢谢
In the main thread I have a Timer
. In the Tick
event I run a BackgroundWorker
. I do some things there and after that BackgroundWorker
calls RunWorkerCompleted
event.
In the main thread I have function Stop
. This function disables the Timer
. But I want wait for BackgroundWorker
when he is working.
For example:
public void Next()
{
// Start the asynchronous operation
if (!this._backgroundWorker.IsBusy)
this._backgroundWorker.RunWorkerAsync();
}
private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
DoSomething();
}
private void _backgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
DoSomethingElse();
}
public void Stop()
{
this._timer.Enabled = false;
}
So my question is how wait for RunWorkerCompleted
event of BackgroundWorker
? I need to wait until DoSomethingElse();
is finished.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
处理 BackgroundWorker.RunWorkerCompleted 事件,该事件发生在后台操作已完成、已取消或引发异常。
Handle the BackgroundWorker.RunWorkerCompleted event which occures when the background operation has completed, has been canceled, or has raised an exception.
如果您只需要两个线程,请允许调用 this._backgroundWorker.RunWorkerAsync(); 的线程。
在调用此方法后死亡,并在 DoSomethingElse() 之后调用任何您想要发生的事情;在如下所示的同一块中
否则您将暂停一个线程以启动另一个线程然后返回,这违背了多线程的目的?
If you only require two threads, allow the thread that called this._backgroundWorker.RunWorkerAsync();
to die after it calls this method and call anything you want to occur after DoSomethingElse(); within the same block as below
Otherwise you are halting a thread to start another and then returning, which defeats the purpose of multiple threads?
我认为BackgroundWorker.IsBusy 属性是在这种情况下唯一可以帮助您的成员。希望下面的逻辑能够满足您的需要。
I think BackgroundWorker.IsBusy property is the only member that can help you in this case. Hope below logic will do what you need.
这是一种停止/冻结主线程直到后台工作完成的方法:
现在,如果您的应用程序使用表单,我将禁用整个表单并显示消息,让用户知道应用程序正在等待进程完成。您还可以使用标志来禁止表单关闭。
Here is a way to stop/freeze the main thread until your background worker finishes:
Now if your application uses a form, I would just disable the whole form and show message letting the user know the the application is waiting for the process to finish. You can also have flag to disable the form from closing.