Partilhar via


RunWorkerCompletedEventArgs Classe

Definição

Fornece dados para o evento MethodNameCompleted .

public ref class RunWorkerCompletedEventArgs : System::ComponentModel::AsyncCompletedEventArgs
public class RunWorkerCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type RunWorkerCompletedEventArgs = class
    inherit AsyncCompletedEventArgs
Public Class RunWorkerCompletedEventArgs
Inherits AsyncCompletedEventArgs
Herança
RunWorkerCompletedEventArgs

Exemplos

O exemplo de código a seguir ilustra o uso de RunWorkerCompletedEventArgs. Este exemplo faz parte de um exemplo maior 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

Ao usar o padrão assíncrono baseado em evento para operações assíncronas, um formulário ou controle do Windows Forms inicia uma operação assíncrona chamando o BackgroundWorker.RunWorkerAsync método. O método, por sua vez, gera o BackgroundWorker.DoWork evento de forma assíncrona e passa uma DoWorkEventArgs instância. Se a operação assíncrona retornar um valor, o BackgroundWorker.DoWork manipulador de eventos normalmente o DoWorkEventArgs.Result atribuirá à propriedade. Quando a operação assíncrona é concluída, o BackgroundWorker.RunWorkerCompleted evento é acionado e passa uma RunWorkerCompletedEventArgs instância que contém informações sobre o status da operação (se ela foi cancelada, com falha ou concluída com êxito). Se for concluída com êxito, sua Result propriedade conterá o valor retornado pela operação assíncrona e atribuído anteriormente à DoWorkEventArgs.Result propriedade.

Observação

O HostProtectionAttribute atributo aplicado a essa classe tem o seguinte Resources valor de propriedade: SharedState. Isso HostProtectionAttribute não afeta aplicativos da área de trabalho (que normalmente são iniciados clicando duas vezes em um ícone, digitando um comando ou inserindo uma URL em um navegador). Para obter mais informações, consulte a HostProtectionAttribute classe ou os atributos de programação e proteção de host do SQL Server.

Construtores

Nome Description
RunWorkerCompletedEventArgs(Object, Exception, Boolean)

Inicializa uma nova instância da classe RunWorkerCompletedEventArgs.

Propriedades

Nome Description
Cancelled

Obtém um valor que indica se uma operação assíncrona foi cancelada.

(Herdado de AsyncCompletedEventArgs)
Error

Obtém um valor que indica qual erro ocorreu durante uma operação assíncrona.

(Herdado de AsyncCompletedEventArgs)
Result

Obtém um valor que representa o resultado de uma operação assíncrona.

UserState

Obtém um valor que representa o estado do usuário.

Métodos

Nome Description
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
RaiseExceptionIfNecessary()

Gerará uma exceção fornecida pelo usuário se uma operação assíncrona falhar.

(Herdado de AsyncCompletedEventArgs)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também