BackgroundWorker.RunWorkerCompleted Evento
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Ocorre quando a operação em segundo plano foi concluída, foi cancelada ou gerou uma exceção.
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
Exemplos
O exemplo de código a seguir demonstra o uso do RunWorkerCompleted evento para lidar com o resultado de uma operação assíncrona. Este exemplo de código faz parte de um exemplo maior fornecido para a 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
Comentários
Esse evento é gerado quando o DoWork manipulador de eventos é retornado.
Se a operação for concluída com êxito e seu resultado for atribuído no DoWork manipulador de eventos, você poderá acessar o resultado por meio da RunWorkerCompletedEventArgs.Result propriedade.
A Error propriedade indica System.ComponentModel.RunWorkerCompletedEventArgs que uma exceção foi gerada pela operação.
A Cancelled propriedade indica System.ComponentModel.RunWorkerCompletedEventArgs se uma solicitação de cancelamento foi processada pela operação em segundo plano. Se o DoWork código no manipulador de System.ComponentModel.RunWorkerCompletedEventArgs eventos detectar uma solicitação de cancelamento verificando o CancellationPending sinalizador e definindo o Cancel sinalizador de System.ComponentModel.DoWorkEventArgs comotrue, o Cancelled sinalizador também será definido como true.
Cuidado
Lembre-se de que seu DoWork código no manipulador de eventos pode concluir seu trabalho à medida que uma solicitação de cancelamento está sendo feita, e seu loop de sondagem pode perder CancellationPending a definição truecomo . Nesse caso, o Cancelled sinalizador do manipulador RunWorkerCompleted de System.ComponentModel.RunWorkerCompletedEventArgs eventos não será definido comotrue, mesmo que uma solicitação de cancelamento tenha sido feita. Essa situação é chamada de condição de corrida e é uma preocupação comum na programação multithreaded. Para obter mais informações sobre problemas de design multithreading, consulte As Práticas Recomendadas de Threading Gerenciado.
O RunWorkerCompleted manipulador de eventos sempre deve verificar as propriedades e AsyncCompletedEventArgs.Cancelled as AsyncCompletedEventArgs.Error propriedades antes de acessar a RunWorkerCompletedEventArgs.Result propriedade. Se uma exceção tiver sido gerada ou se a operação tiver sido cancelada, acessar a RunWorkerCompletedEventArgs.Result propriedade gerará uma exceção.