Поделиться через


BackgroundWorker.RunWorkerCompleted Событие

Определение

Происходит при завершении фоновой операции, отмене или возникновении исключения.

public:
 event System::ComponentModel::RunWorkerCompletedEventHandler ^ RunWorkerCompleted;
public event System.ComponentModel.RunWorkerCompletedEventHandler RunWorkerCompleted;
public event System.ComponentModel.RunWorkerCompletedEventHandler? RunWorkerCompleted;
member this.RunWorkerCompleted : System.ComponentModel.RunWorkerCompletedEventHandler 
Public Custom Event RunWorkerCompleted As RunWorkerCompletedEventHandler 

Тип события

Примеры

В следующем примере кода показано использование RunWorkerCompleted события для обработки результата асинхронной операции. Этот пример кода является частью более крупного примера, предоставленного для BackgroundWorker класса.

// This event handler deals with the results of the
// background operation.
void backgroundWorker1_RunWorkerCompleted( Object^ /*sender*/, RunWorkerCompletedEventArgs^ e )
{
   // First, handle the case where an exception was thrown.
   if ( e->Error != nullptr )
   {
      MessageBox::Show( e->Error->Message );
   }
   else
   if ( e->Cancelled )
   {
      // Next, handle the case where the user cancelled 
      // 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 = "Cancelled";
   }
   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;
}
// This event handler deals with the results of the
// background operation.
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.
    numericUpDown1.Enabled = true;

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

    // Disable the Cancel button.
    cancelAsyncButton.Enabled = false;
}
' This event handler deals with the results of the
' background operation.
Private Sub backgroundWorker1_RunWorkerCompleted(
ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
Handles backgroundWorker1.RunWorkerCompleted

    ' First, handle the case where an exception was thrown.
    If (e.Error IsNot Nothing) Then
        MessageBox.Show(e.Error.Message)
    ElseIf e.Cancelled Then
        ' 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()
    End If

    ' Enable the UpDown control.
    numericUpDown1.Enabled = True

    ' Enable the Start button.
    startAsyncButton.Enabled = True

    ' Disable the Cancel button.
    cancelAsyncButton.Enabled = False
End Sub

Комментарии

Это событие возникает при возврате обработчика DoWork событий.

Если операция завершается успешно, а результат назначается в DoWork обработчике событий, вы можете получить доступ к результату RunWorkerCompletedEventArgs.Result через свойство.

Свойство ErrorSystem.ComponentModel.RunWorkerCompletedEventArgs указывает, что исключение было создано операцией.

Свойство CancelledSystem.ComponentModel.RunWorkerCompletedEventArgs указывает, был ли запрос на отмену обработан фоновой операцией. Если код в обработчике DoWork событий обнаруживает запрос на отмену, проверив CancellationPending флаг и задав Cancel флаг, trueSystem.ComponentModel.RunWorkerCompletedEventArgsSystem.ComponentModel.DoWorkEventArgsCancelled флаг также будет установлен.true

Предостережение

Помните, что код в обработчике DoWork событий может завершить работу в качестве запроса на отмену, и ваш цикл опроса может не CancellationPending иметь значения true. В этом случае Cancelled флаг System.ComponentModel.RunWorkerCompletedEventArgs в обработчике RunWorkerCompleted событий не будет задан true, даже если был выполнен запрос на отмену. Эта ситуация называется состоянием гонки и является распространенной проблемой в многопоточных программированиях. Дополнительные сведения о проблемах проектирования с несколькими потоками см. в статье "Рекомендации по управлению потоками".

Обработчик RunWorkerCompleted событий всегда должен проверять AsyncCompletedEventArgs.Error свойства и AsyncCompletedEventArgs.Cancelled свойства перед доступом к свойству RunWorkerCompletedEventArgs.Result . Если возникло исключение или если операция была отменена, доступ к RunWorkerCompletedEventArgs.Result свойству вызывает исключение.

Применяется к

См. также раздел