RunWorkerCompletedEventArgs Classe
Definição
Fornece dados para o evento MethodName Completed .Provides data for the MethodNameCompleted event.
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
Exemplos
O exemplo de código a seguir ilustra o uso do objeto RunWorkerCompletedEventArgs.The following code example illustrates the use of RunWorkerCompletedEventArgs. Este exemplo faz parte de um exemplo maior para a BackgroundWorker classe.This example is part of a larger sample 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
Comentários
Ao usar o padrão assíncrono baseado em evento para operações assíncronas, um Windows Forms formulário ou controle inicia uma operação assíncrona chamando o BackgroundWorker.RunWorkerAsync método.When using the event-based asynchronous pattern for asynchronous operations, a Windows Forms form or control initiates an asynchronous operation by calling the BackgroundWorker.RunWorkerAsync method. O método, por sua vez BackgroundWorker.DoWork , gera o evento de forma assíncrona e passa a ele uma DoWorkEventArgs instância.The method in turn raises the BackgroundWorker.DoWork event asynchronously and passes it a DoWorkEventArgs instance. Se a operação assíncrona retornar um valor, o BackgroundWorker.DoWork manipulador de eventos normalmente o atribuirá à DoWorkEventArgs.Result propriedade.If the asynchronous operation returns a value, the BackgroundWorker.DoWork event handler typically assigns it to the DoWorkEventArgs.Result property. Quando a operação assíncrona é concluída, o BackgroundWorker.RunWorkerCompleted evento é gerado e passa uma RunWorkerCompletedEventArgs instância que contém informações sobre o status da operação (se ela foi cancelada, falhou ou concluída com êxito).When the asynchronous operation completes, the BackgroundWorker.RunWorkerCompleted event is raised and is passed a RunWorkerCompletedEventArgs instance that contains information about the status of the operation (whether it was cancelled, faulted, or completed successfully). Se for concluído com êxito, sua Result Propriedade conterá o valor retornado pela operação assíncrona e anteriormente atribuída à DoWorkEventArgs.Result propriedade.If it completed successfully, its Result property contains the value returned by the asynchronous operation and previously assigned to the DoWorkEventArgs.Result property.
Observação
O HostProtectionAttribute atributo aplicado a essa classe tem o seguinte Resources valor de propriedade: SharedState .The HostProtectionAttribute attribute applied to this class has the following Resources property value: SharedState. HostProtectionAttribute não afeta aplicativos de área de trabalho (que são normalmente iniciados com o clique duplo em um ícone, a digitação de um comando ou a inserção de uma URL em um navegador).The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). Para obter mais informações, consulte a HostProtectionAttribute classe ou os atributos de proteção de host e de programação de SQL Server.For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Construtores
| RunWorkerCompletedEventArgs(Object, Exception, Boolean) |
Inicializa uma nova instância da classe RunWorkerCompletedEventArgs.Initializes a new instance of the RunWorkerCompletedEventArgs class. |
Propriedades
| Cancelled |
Obtém um valor que indica se uma operação assíncrona foi cancelada.Gets a value indicating whether an asynchronous operation has been canceled. (Herdado de AsyncCompletedEventArgs) |
| Error |
Obtém um valor que indica qual erro ocorreu durante uma operação assíncrona.Gets a value indicating which error occurred during an asynchronous operation. (Herdado de AsyncCompletedEventArgs) |
| Result |
Obtém um valor que representa o resultado de uma operação assíncrona.Gets a value that represents the result of an asynchronous operation. |
| UserState |
Obtém um valor que representa o estado do usuário.Gets a value that represents the user state. |
Métodos
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| RaiseExceptionIfNecessary() |
Gera uma exceção fornecida pelo usuário se uma operação assíncrona falhou.Raises a user-supplied exception if an asynchronous operation failed. (Herdado de AsyncCompletedEventArgs) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |