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.Occurs when the background operation has completed, has been canceled, or has raised an exception.

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

Ejemplos

En el ejemplo de código siguiente se muestra el uso del evento RunWorkerCompleted para controlar el resultado de una operación asincrónica.The following code example demonstrates the use of the RunWorkerCompleted event to handle the result of an asynchronous operation. Este ejemplo de código forma parte de un ejemplo más extenso proporcionado para la clase BackgroundWorker.This code example is part of a larger example provided for the BackgroundWorker class.

// 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 desencadena cuando el controlador de eventos DoWork devuelve.This event is raised when the DoWork event handler returns.

Si la operación se completa correctamente y su resultado se asigna en el controlador de eventos DoWork, puede tener acceso al resultado a través de la propiedad RunWorkerCompletedEventArgs.Result.If the operation completes successfully and its result is assigned in the DoWork event handler, you can access the result through the RunWorkerCompletedEventArgs.Result property.

La propiedad Error de System.ComponentModel.RunWorkerCompletedEventArgs indica que la operación produjo una excepción.The Error property of System.ComponentModel.RunWorkerCompletedEventArgs indicates that an exception was thrown by the operation.

La propiedad Cancelled de System.ComponentModel.RunWorkerCompletedEventArgs indica si la operación en segundo plano procesó una solicitud de cancelación.The Cancelled property of System.ComponentModel.RunWorkerCompletedEventArgs indicates whether a cancellation request was processed by the background operation. Si el código del controlador de eventos DoWork detecta una solicitud de cancelación comprobando la marca de CancellationPending y estableciendo la marca Cancel de System.ComponentModel.DoWorkEventArgs en true, la marca Cancelled de System.ComponentModel.RunWorkerCompletedEventArgs también se establecerá en true.If your code in the DoWork event handler detects a cancellation request by checking the CancellationPending flag and setting the Cancel flag of System.ComponentModel.DoWorkEventArgs to true, the Cancelled flag of System.ComponentModel.RunWorkerCompletedEventArgs also will be set to true.

Precaución

Tenga en cuenta que el código del controlador de eventos DoWork puede finalizar su trabajo a medida que se realiza una solicitud de cancelación, y que el bucle de sondeo puede pasar por alto CancellationPending establecerse en true.Be aware that your code in the DoWork event handler may finish its work as a cancellation request is being made, and your polling loop may miss CancellationPending being set to true. En este caso, la marca de Cancelled de System.ComponentModel.RunWorkerCompletedEventArgs en el controlador de eventos de RunWorkerCompleted no se establecerá en true, aunque se haya realizado una solicitud de cancelación.In this case, the Cancelled flag of System.ComponentModel.RunWorkerCompletedEventArgs in your RunWorkerCompleted event handler will not be set to true, even though a cancellation request was made. Esta situación se denomina condición de carrera y es un problema habitual en la programación multiproceso.This situation is called a race condition and is a common concern in multithreaded programming. Para obtener más información sobre los problemas de diseño de multithreading, vea procedimientos recomendados para el subprocesamiento administrado.For more information about multithreading design issues, see Managed Threading Best Practices.

El controlador de eventos de RunWorkerCompleted siempre debe comprobar las propiedades AsyncCompletedEventArgs.Error y AsyncCompletedEventArgs.Cancelled antes de tener acceso a la propiedad RunWorkerCompletedEventArgs.Result.Your RunWorkerCompleted event handler should always check the AsyncCompletedEventArgs.Error and AsyncCompletedEventArgs.Cancelled properties before accessing the RunWorkerCompletedEventArgs.Result property. Si se ha producido una excepción o si se ha cancelado la operación, el acceso a la propiedad RunWorkerCompletedEventArgs.Result produce una excepción.If an exception was raised or if the operation was canceled, accessing the RunWorkerCompletedEventArgs.Result property raises an exception.

Se aplica a

Consulte también: