Partager via


BackgroundWorker.RunWorkerCompleted Événement

Définition

Se produit lorsque l’opération en arrière-plan est terminée, a été annulée ou a déclenché une exception.

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 

Type d'événement

Exemples

L’exemple de code suivant illustre l’utilisation de l’événement RunWorkerCompleted pour gérer le résultat d’une opération asynchrone. Cet exemple de code fait partie d’un exemple plus grand fourni pour la BackgroundWorker classe.

// 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

Remarques

Cet événement est déclenché lorsque le DoWork gestionnaire d’événements retourne.

Si l’opération se termine correctement et que son résultat est affecté dans le DoWork gestionnaire d’événements, vous pouvez accéder au résultat via la RunWorkerCompletedEventArgs.Result propriété.

La Error propriété de System.ComponentModel.RunWorkerCompletedEventArgs indique qu’une exception a été levée par l’opération.

Propriété Cancelled indiquant System.ComponentModel.RunWorkerCompletedEventArgs si une demande d’annulation a été traitée par l’opération en arrière-plan. Si votre code dans le DoWork gestionnaire d’événements détecte une demande d’annulation en vérifiant l’indicateur CancellationPending et en définissant l’indicateur Cancel sur System.ComponentModel.DoWorkEventArgstrue, l’indicateur Cancelled de System.ComponentModel.RunWorkerCompletedEventArgs également est défini sur true.

Avertissement

N’oubliez pas que votre code dans le DoWork gestionnaire d’événements peut terminer son travail en tant que demande d’annulation en cours d’exécution, et que votre boucle d’interrogation peut manquer CancellationPending d’être définie truesur . Dans ce cas, l’indicateur Cancelled de votre RunWorkerCompleted gestionnaire d’événements System.ComponentModel.RunWorkerCompletedEventArgs n’est pas défini truesur , même si une demande d’annulation a été effectuée. Cette situation est appelée une condition de concurrence et est une préoccupation commune dans la programmation multithread. Pour plus d’informations sur les problèmes de conception multithreading, consultez Les meilleures pratiques en matière de threads managés.

Votre RunWorkerCompleted gestionnaire d’événements doit toujours vérifier les propriétés et AsyncCompletedEventArgs.Cancelled les AsyncCompletedEventArgs.Error propriétés avant d’accéder à la RunWorkerCompletedEventArgs.Result propriété. Si une exception a été levée ou si l’opération a été annulée, l’accès à la RunWorkerCompletedEventArgs.Result propriété déclenche une exception.

S’applique à

Voir aussi