BackgroundWorker.RunWorkerCompleted Evento

Definición

Se produce cuando la operación en segundo plano se ha completado, se ha cancelado o ha producido una excepción.

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 

Tipo de evento

Ejemplos

En el ejemplo de código siguiente se muestra el uso del RunWorkerCompleted evento para controlar el resultado de una operación asincrónica. Este ejemplo de código es parte de un ejemplo más grande proporcionado para la clase 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.
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;
}
' 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.
    Me.numericUpDown1.Enabled = True

    ' Enable the Start button.
    startAsyncButton.Enabled = True

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

Comentarios

Este evento se genera cuando el DoWork controlador de eventos devuelve.

Si la operación se completa correctamente y su resultado se asigna en el DoWork controlador de eventos, puede acceder al resultado a través de la RunWorkerCompletedEventArgs.Result propiedad .

La Error propiedad de System.ComponentModel.RunWorkerCompletedEventArgs indica que la operación produjo una excepción.

La Cancelled propiedad de System.ComponentModel.RunWorkerCompletedEventArgs indica si la operación en segundo plano procesó una solicitud de cancelación. Si el código del DoWork controlador de eventos detecta una solicitud de cancelación comprobando la CancellationPending marca y estableciendo la Cancel marca de trueSystem.ComponentModel.DoWorkEventArgs en , la Cancelled marca de System.ComponentModel.RunWorkerCompletedEventArgs también se establecerá en true.

Precaución

Tenga en cuenta que el código del DoWork controlador de eventos puede finalizar su trabajo a medida que se realiza una solicitud de cancelación y es posible que el bucle de sondeo no CancellationPending se establezca trueen . En este caso, la Cancelled marca de en el RunWorkerCompleted controlador de System.ComponentModel.RunWorkerCompletedEventArgs eventos no se establecerá trueen , aunque se haya realizado una solicitud de cancelación. Esta situación se denomina condición de carrera y es una preocupación común en la programación multiproceso. Para obtener más información sobre los problemas de diseño de multithreading, consulte Procedimientos recomendados para subprocesos administrados.

El RunWorkerCompleted controlador de eventos siempre debe comprobar las AsyncCompletedEventArgs.Error propiedades y AsyncCompletedEventArgs.Cancelled antes de acceder a la RunWorkerCompletedEventArgs.Result propiedad . Si se generó una excepción o si se canceló la operación, el acceso a la RunWorkerCompletedEventArgs.Result propiedad genera una excepción.

Se aplica a

Consulte también