c# - 等待BackgroundWorker RunWorkerCompleted

标签 c# .net multithreading backgroundworker

在主线程中我有一个计时器。在 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;
}

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

谢谢

最佳答案

处理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.
    }

}

关于c# - 等待BackgroundWorker RunWorkerCompleted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5921437/

相关文章:

c# - 排序列表<String[]>

c# - 如何使用 Linq 查询和 EF 从具有多个字段的表中仅检索一个字段

c# - 验证项目控件中项目的数据模板

C# MySQL 连接 - 多线程 - 无法连接

c# - C# 是否具有 "ThreadLocal"属性的 "ThreadStatic"模拟(对于数据成员)?

javascript - 如何重置 UWP WebView 的内容缩放因子

c# - 我可以不使用 try catch() 来忽略错误吗?

.net - DocumentViewer 工具栏和上下文菜单

.net - 调用上下文菜单打开

java - 透明扫描仪(中)