首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >等待BackgroundWorker RunWorkerCompleted

等待BackgroundWorker RunWorkerCompleted
EN

Stack Overflow用户
提问于 2011-05-07 21:43:41
回答 4查看 5.8K关注 0票数 2

在主线程中,我有一个Timer。在Tick事件中,我运行一个BackgroundWorker。我在那里做了一些事情,在那之后BackgroundWorker调用RunWorkerCompleted事件。

在主线程中,我有Stop函数。此功能禁用Timer。但是我想在BackgroundWorker工作的时候等他。

例如:

代码语言:javascript
运行
复制
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;
}

所以我的问题是如何等待BackgroundWorkerRunWorkerCompleted事件?我需要等到DoSomethingElse();完成。

谢谢

EN

回答 4

Stack Overflow用户

发布于 2011-05-07 21:53:20

处理后台操作完成、取消或引发异常时发生的BackgroundWorker.RunWorkerCompleted事件。

代码语言:javascript
运行
复制
// 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.
    }

}
票数 2
EN

Stack Overflow用户

发布于 2011-05-07 21:51:49

如果只需要两个线程,则允许调用this._backgroundWorker.RunWorkerAsync();的线程在调用此方法后终止,并在同一块中的DoSomethingElse();之后调用您希望发生的任何事情,如下所示

代码语言:javascript
运行
复制
        private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

DoSomethingElse();
DoSomethingAfterSomethingElse();

        }

否则,您将停止一个线程以启动另一个线程,然后返回,这就违背了多线程的目的?

票数 1
EN

Stack Overflow用户

发布于 2011-05-08 06:54:50

我认为在这种情况下,BackgroundWorker.IsBusy属性是唯一可以帮助您的成员。希望下面的逻辑能满足你的需要。

代码语言:javascript
运行
复制
//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;
    }
} 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5921437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档