Evaluar y enviar comentarios
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Biblioteca de clases de .NET Framework
BackgroundWorker.RunWorkerCompleted (Evento)

Nota: este evento es nuevo en la versión 2.0 de .NET Framework.

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

Espacio de nombres: System.ComponentModel
Ensamblado: System (en system.dll)

Visual Basic (Declaración)
Public Event RunWorkerCompleted As RunWorkerCompletedEventHandler
Visual Basic (Uso)
Dim instance As BackgroundWorker
Dim handler As RunWorkerCompletedEventHandler

AddHandler instance.RunWorkerCompleted, handler
C#
public event RunWorkerCompletedEventHandler RunWorkerCompleted
C++
public:
event RunWorkerCompletedEventHandler^ RunWorkerCompleted {
    void add (RunWorkerCompletedEventHandler^ value);
    void remove (RunWorkerCompletedEventHandler^ value);
}
J#
/** @event */
public void add_RunWorkerCompleted (RunWorkerCompletedEventHandler value)

/** @event */
public void remove_RunWorkerCompleted (RunWorkerCompletedEventHandler value)
JScript
JScript admite el uso de eventos, pero no admite la declaración de eventos nuevos.

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

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

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

La propiedad Cancelled de System.ComponentModel.RunWorkerCompletedEventArgs indica si la operación en segundo plano ha procesado una solicitud de la cancelación. Si el código del controlador de eventos DoWork detecta una solicitud de cancelación mediante la comprobación del indicador CancellationPending y el establecimiento del indicador Cancel de System.ComponentModel.DoWorkEventArgs en true, el indicador Cancelled de System.ComponentModel.RunWorkerCompletedEventArgs también se establecerá en true.

Nota de precauciónPrecaución

Tenga en cuenta que el código del controlador de eventos DoWork puede finalizar su trabajo mientras se realiza una solicitud de cancelación y que el bucle de sondeo podría pasar por alto la propiedad CancellationPending que se haya establecido en true. En este caso, el indicador Cancelled del objeto System.ComponentModel.RunWorkerCompletedEventArgs del controlador de eventos RunWorkerCompleted no se establecerá en true aunque se haya realizado una solicitud de cancelación. Esta situación se denomina condición de anticipación y es un problema habitual en la programación con subprocesamiento múltiple. Para obtener más información sobre los problemas de diseño de subprocesamiento múltiple, vea Procedimientos recomendados para el subprocesamiento administrado.

El controlador de eventos RunWorkerCompleted debe comprobar siempre las propiedades AsyncCompletedEventArgs.Error y AsyncCompletedEventArgs.Cancelled antes de obtener acceso a la propiedad RunWorkerCompletedEventArgs.Result. Si se ha producido una excepción o si se ha cancelado la operación, el acceso a la propiedad RunWorkerCompletedEventArgs.Result provoca una excepción.

En el ejemplo de código siguiente se muestra el uso del evento RunWorkerCompleted para controlar el resultado de una operación asincrónica. Este ejemplo de código forma parte de un ejemplo más extenso referente a la clase BackgroundWorker.

Visual Basic
' 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 Not (e.Error Is 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 'backgroundWorker1_RunWorkerCompleted
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;
}
C++
// 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;
}
J#
// 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.get_Error() != null) {
    
        MessageBox.Show(e.get_Error().get_Message());
    }
    else {
    
        if (e.get_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.set_Text("Cancelled");
        }
        else {
        
            // Finally, handle the case where the operation 
            // succeeded.
            resultLabel.set_Text(e.get_Result().ToString());
        }
    }

    // Enable the UpDown control.
    this.numericUpDown1.set_Enabled(true);

    // Enable the Start button.
    startAsyncButton.set_Enabled(true);

    // Disable the Cancel button.
    cancelAsyncButton.set_Enabled(false);
} //backgroundWorker1_RunWorkerCompleted

Windows 98, Windows 2000 SP4, Windows Millennium, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2008 Microsoft Corporation. Reservados todos los derechos. Términos de uso  |  Marcas Registradas  |  Privacidad
Page view tracker