BackgroundWorker.RunWorkerCompleted 事件

定义

当后台操作已完成、被取消或引发异常时发生。

C#
public event System.ComponentModel.RunWorkerCompletedEventHandler RunWorkerCompleted;
C#
public event System.ComponentModel.RunWorkerCompletedEventHandler? RunWorkerCompleted;

事件类型

示例

下面的代码示例演示如何使用 RunWorkerCompleted 事件来处理异步操作的结果。 此代码示例是为 BackgroundWorker 类提供的一个更大示例的一部分。

C#
// 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)
    {
        MessageBox.Show(e.Error.Message);
    }
    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.
        resultLabel.Text = "Canceled";
    }
    else
    {
        // Finally, handle the case where the operation 
        // succeeded.
        resultLabel.Text = e.Result.ToString();
    }

    // Enable the UpDown control.
    this.numericUpDown1.Enabled = true;

    // Enable the Start button.
    startAsyncButton.Enabled = true;

    // Disable the Cancel button.
    cancelAsyncButton.Enabled = false;
}

注解

当事件处理程序返回时, DoWork 将引发此事件。

如果操作成功完成并在事件处理程序中 DoWork 分配了其结果,则可以通过 属性访问结果 RunWorkerCompletedEventArgs.Result

ErrorSystem.ComponentModel.RunWorkerCompletedEventArgs 属性指示操作引发了异常。

CancelledSystem.ComponentModel.RunWorkerCompletedEventArgs 属性指示取消请求是否由后台操作处理。 如果事件处理程序中的DoWork代码通过检查 CancellationPending 标志并将 的 System.ComponentModel.DoWorkEventArgs 标志设置为 Canceltrue来检测到取消请求,则 CancelledSystem.ComponentModel.RunWorkerCompletedEventArgs 标志也将设置为 true

注意

请注意,事件处理程序中的 DoWork 代码可能会在发出取消请求时完成其工作,并且轮询循环可能会错过 CancellationPending 设置为 true。 在这种情况下,即使发出了取消请求,Cancelled事件处理程序中的 RunWorkerCompleted 标志System.ComponentModel.RunWorkerCompletedEventArgs也不会设置为 true。 这种情况称为 争用条件 ,是多线程编程中常见的问题。 有关多线程设计问题的详细信息,请参阅 托管线程处理最佳做法

RunWorkerCompleted访问 RunWorkerCompletedEventArgs.Result 属性之前,AsyncCompletedEventArgs.Error事件处理程序应始终检查 和 AsyncCompletedEventArgs.Cancelled 属性。 如果引发异常或取消操作,则 RunWorkerCompletedEventArgs.Result 访问 属性将引发异常。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

另请参阅