在主线程中,我有一个Timer。在Tick事件中,我运行一个BackgroundWorker。我在那里做了一些事情,在那之后BackgroundWorker调用RunWorkerCompleted事件。
在主线程中,我有Stop函数。此功能禁用Timer。但是我想在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();完成。
谢谢
发布于 2011-05-07 21:53:20
处理后台操作完成、取消或引发异常时发生的BackgroundWorker.RunWorkerCompleted事件。
// This event handler deals with the results of the
// background operation.
private void backgroundWorker1_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
}
else if (e.Cancelled)
{
// Next, handle the case where the user canceled
// the operation.
// Note that due to a race condition in
// the DoWork event handler, the Cancelled
// flag may not have been set, even though
// CancelAsync was called.
}
else
{
// Finally, handle the case where the operation
// succeeded.
}
}发布于 2011-05-07 21:51:49
如果只需要两个线程,则允许调用this._backgroundWorker.RunWorkerAsync();的线程在调用此方法后终止,并在同一块中的DoSomethingElse();之后调用您希望发生的任何事情,如下所示
private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DoSomethingElse();
DoSomethingAfterSomethingElse();
}否则,您将停止一个线程以启动另一个线程,然后返回,这就违背了多线程的目的?
发布于 2011-05-08 06:54:50
我认为在这种情况下,BackgroundWorker.IsBusy属性是唯一可以帮助您的成员。希望下面的逻辑能满足你的需要。
//Add a class member
private bool stopped;
public void Stop()
{
if (!this._backgroundWorker.IsBusy)
{
this._timer.Enabled = false;
stopped = false;
}
else
{
stopped = true;
}
}
private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DoSomethingElse();
if (stopped)
{
this._timer.Enabled = false;
stopped = false;
}
} https://stackoverflow.com/questions/5921437
复制相似问题