BackgroundWorker.RunWorkerCompleted Evento
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Ocorre quando a operação em segundo plano foi concluída, foi cancelada ou levantou uma exceção.
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 seguinte demonstra a utilização 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
Observações
Este evento é levantado quando o DoWork gestor de eventos regressa.
Se a operação for concluída com sucesso e o seu resultado for atribuído no DoWork gestor de eventos, pode aceder ao resultado através da RunWorkerCompletedEventArgs.Result propriedade.
A Error propriedade de System.ComponentModel.RunWorkerCompletedEventArgs indica que foi lançada uma exceção pela operação.
A Cancelled propriedade de System.ComponentModel.RunWorkerCompletedEventArgs indica se um pedido de cancelamento foi processado pela operação em segundo plano. Se o seu código no DoWork handler de eventos detetar um pedido de cancelamento ao verificar a CancellationPending flag e definir a Cancel flag de System.ComponentModel.DoWorkEventArgs para true, a Cancelled flag de System.ComponentModel.RunWorkerCompletedEventArgs também será definida para true.
Atenção
Tenha em atenção que o seu código no DoWork handler de eventos pode terminar o seu trabalho enquanto um pedido de cancelamento está a ser feito, e o seu ciclo de sondagens pode não CancellationPending ter sido definido para true. Neste caso, a Cancelled flag de System.ComponentModel.RunWorkerCompletedEventArgs no teu RunWorkerCompleted gestor de eventos não será definida para true, mesmo que tenha sido feito um pedido de cancelamento. Esta situação é chamada condição de corrida e é uma preocupação comum na programação multithread. Para mais informações sobre questões de design de multithreading, consulte Melhores Práticas de Gestão de Threading.
O seu RunWorkerCompleted gestor de eventos deve sempre verificar as AsyncCompletedEventArgs.Error propriedades e AsyncCompletedEventArgs.Cancelled antes de aceder à RunWorkerCompletedEventArgs.Result propriedade. Se foi levantada uma exceção ou se a operação foi cancelada, o acesso à RunWorkerCompletedEventArgs.Result propriedade gera uma exceção.