BackgroundWorker.RunWorkerCompleted Event

Definition

Viene generato quando l'operazione in background è stata annullata o ha generato un'eccezione.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 

Examples

Nell'esempio di codice riportato di seguito viene illustrato l'utilizzo dell'evento RunWorkerCompleted per gestire il risultato di un'operazione asincrona.The following code example demonstrates the use of the RunWorkerCompleted event to handle the result of an asynchronous operation. Questo esempio di codice fa parte di un esempio più ampio fornito per la classe 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

Remarks

Questo evento viene generato quando viene restituito il gestore dell'evento DoWork.This event is raised when the DoWork event handler returns.

Se l'operazione viene completata correttamente e il risultato viene assegnato nel gestore dell'evento DoWork, è possibile accedere al risultato tramite la proprietà 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 proprietà Error di System.ComponentModel.RunWorkerCompletedEventArgs indica che è stata generata un'eccezione dall'operazione.The Error property of System.ComponentModel.RunWorkerCompletedEventArgs indicates that an exception was thrown by the operation.

La proprietà Cancelled di System.ComponentModel.RunWorkerCompletedEventArgs indica se una richiesta di annullamento è stata elaborata dall'operazione in background.The Cancelled property of System.ComponentModel.RunWorkerCompletedEventArgs indicates whether a cancellation request was processed by the background operation. Se il codice nel gestore dell'evento DoWork rileva una richiesta di annullamento controllando il flag di CancellationPending e impostando il flag di Cancel di System.ComponentModel.DoWorkEventArgs su true, il flag di Cancelled di System.ComponentModel.RunWorkerCompletedEventArgs verrà impostato su 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.

Caution

Tenere presente che il codice nel gestore dell'evento DoWork può terminare il proprio lavoro mentre è in corso una richiesta di annullamento e il ciclo di polling potrebbe non riuscire CancellationPending essere impostato su 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. In questo caso, il flag di Cancelled di System.ComponentModel.RunWorkerCompletedEventArgs nel gestore dell'evento RunWorkerCompleted non verrà impostato su true, anche se è stata effettuata una richiesta di annullamento.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. Questa situazione viene definita race condition e costituisce un problema comune nella programmazione multithreading.This situation is called a race condition and is a common concern in multithreaded programming. Per ulteriori informazioni sui problemi di progettazione del multithreading, vedere procedure consigliate per il threading gestito.For more information about multithreading design issues, see Managed Threading Best Practices.

Il gestore dell'evento RunWorkerCompleted deve sempre controllare le proprietà AsyncCompletedEventArgs.Error e AsyncCompletedEventArgs.Cancelled prima di accedere alla proprietà RunWorkerCompletedEventArgs.Result.Your RunWorkerCompleted event handler should always check the AsyncCompletedEventArgs.Error and AsyncCompletedEventArgs.Cancelled properties before accessing the RunWorkerCompletedEventArgs.Result property. Se è stata generata un'eccezione o se l'operazione è stata annullata, l'accesso alla proprietà RunWorkerCompletedEventArgs.Result genera un'eccezione.If an exception was raised or if the operation was canceled, accessing the RunWorkerCompletedEventArgs.Result property raises an exception.

Applies to

See also