BackgroundWorker.DoWork BackgroundWorker.DoWork BackgroundWorker.DoWork BackgroundWorker.DoWork Event

Definición

Se produce cuando se llama a RunWorkerAsync().Occurs when RunWorkerAsync() is called.

public:
 event System::ComponentModel::DoWorkEventHandler ^ DoWork;
public event System.ComponentModel.DoWorkEventHandler DoWork;
member this.DoWork : System.ComponentModel.DoWorkEventHandler 
Public Custom Event DoWork As DoWorkEventHandler 

Ejemplos

En el ejemplo de código siguiente se muestra el uso de la DoWork evento para iniciar una operación asincrónica.The following code example demonstrates the use of the DoWork event to start an asynchronous operation. Este ejemplo de código forma parte de un ejemplo más extenso proporcionado para el BackgroundWorker clase.This code example is part of a larger example provided for the BackgroundWorker class.

// This event handler is where the actual,
// potentially time-consuming work is done.
void backgroundWorker1_DoWork( Object^ sender, DoWorkEventArgs^ e )
{
   // Get the BackgroundWorker that raised this event.
   BackgroundWorker^ worker = dynamic_cast<BackgroundWorker^>(sender);

   // Assign the result of the computation
   // to the Result property of the DoWorkEventArgs
   // object. This is will be available to the 
   // RunWorkerCompleted eventhandler.
   e->Result = ComputeFibonacci( safe_cast<Int32>(e->Argument), worker, e );
}
// This event handler is where the actual,
// potentially time-consuming work is done.
private void backgroundWorker1_DoWork(object sender, 
    DoWorkEventArgs e)
{   
    // Get the BackgroundWorker that raised this event.
    BackgroundWorker worker = sender as BackgroundWorker;

    // Assign the result of the computation
    // to the Result property of the DoWorkEventArgs
    // object. This is will be available to the 
    // RunWorkerCompleted eventhandler.
    e.Result = ComputeFibonacci((int)e.Argument, worker, e);
}
' This event handler is where the actual work is done.
Private Sub backgroundWorker1_DoWork( _
ByVal sender As Object, _
ByVal e As DoWorkEventArgs) _
Handles backgroundWorker1.DoWork

    ' Get the BackgroundWorker object that raised this event.
    Dim worker As BackgroundWorker = _
        CType(sender, BackgroundWorker)

    ' Assign the result of the computation
    ' to the Result property of the DoWorkEventArgs
    ' object. This is will be available to the 
    ' RunWorkerCompleted eventhandler.
    e.Result = ComputeFibonacci(e.Argument, worker, e)
End Sub 'backgroundWorker1_DoWork

Comentarios

Este evento se desencadena cuando se llama a la RunWorkerAsync método.This event is raised when you call the RunWorkerAsync method. Esto es donde se inicia la operación que realiza el trabajo puede requerir mucho tiempo.This is where you start the operation that performs the potentially time-consuming work.

El código en el DoWork controlador de eventos debe comprobar periódicamente el CancellationPending valor de propiedad y anular la operación si es true.Your code in the DoWork event handler should periodically check the CancellationPending property value and abort the operation if it is true. Cuando esto ocurre, puede establecer el Cancel marca de System.ComponentModel.DoWorkEventArgs a truey el Cancelled marca de System.ComponentModel.RunWorkerCompletedEventArgs en su RunWorkerCompleted controlador de eventos se establecerá en true.When this occurs, you can set the Cancel flag of System.ComponentModel.DoWorkEventArgs to true, and the Cancelled flag of System.ComponentModel.RunWorkerCompletedEventArgs in your RunWorkerCompleted event handler will be set to true.

Precaución

Tenga en cuenta que el código en el DoWork controlador de eventos puede finalizar su trabajo mientras se realiza una solicitud de cancelación y el bucle de sondeo puede perder CancellationPending se establece en true.Be aware that your code in the DoWork event handler may finish its work as a cancellation request is being made, and your polling loop may miss CancellationPending being set to true. En este caso, el Cancelled marca de System.ComponentModel.RunWorkerCompletedEventArgs en su RunWorkerCompleted controlador de eventos no se establecerá en true, aunque se realizó una solicitud de cancelación.In this case, the Cancelled flag of System.ComponentModel.RunWorkerCompletedEventArgs in your RunWorkerCompleted event handler will not be set to true, even though a cancellation request was made. Esta situación se denomina un condición de carrera y es un problema habitual en la programación multiproceso.This situation is called a race condition and is a common concern in multithreaded programming. Para obtener más información sobre el diseño multithreading problemas, vea Managed Threading Best Practices.For more information about multithreading design issues, see Managed Threading Best Practices.

Si la operación genera un resultado, puede asignar el resultado a la DoWorkEventArgs.Result propiedad.If your operation produces a result, you can assign the result to the DoWorkEventArgs.Result property. Esta opción estará disponible para el RunWorkerCompleted controlador de eventos en el RunWorkerCompletedEventArgs.Result propiedad.This will be available to the RunWorkerCompleted event handler in the RunWorkerCompletedEventArgs.Result property.

Si la operación provoca una excepción que el código no controla, el BackgroundWorker detecta la excepción y la pasa a la RunWorkerCompleted controlador de eventos, donde se expone como la Error propiedad de System.ComponentModel.RunWorkerCompletedEventArgs.If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel.RunWorkerCompletedEventArgs. Si está ejecutando en el depurador de Visual Studio, el depurador se interrumpirá en el punto en el DoWork controlador de eventos que se generó la excepción no controlada.If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised. Si tiene más de una BackgroundWorker, no debe hacer referencia alguno de ellos directamente, ya que esto uniría la DoWork controlador de eventos a una instancia específica de BackgroundWorker.If you have more than one BackgroundWorker, you should not reference any of them directly, as this would couple your DoWork event handler to a specific instance of BackgroundWorker. En su lugar, debe tener acceso a su BackgroundWorker convirtiendo el sender parámetro en su DoWork controlador de eventos.Instead, you should access your BackgroundWorker by casting the sender parameter in your DoWork event handler.

Debe tener cuidado para no manipular los objetos de interfaz de usuario en su DoWork controlador de eventos.You must be careful not to manipulate any user-interface objects in your DoWork event handler. En su lugar, se comunican con la interfaz de usuario a través de la BackgroundWorker eventos.Instead, communicate to the user interface through the BackgroundWorker events.

Para obtener más información acerca de cómo controlar eventos, vea controlar y provocar eventos.For more information about how to handle events, see Handling and Raising Events.

Se aplica a

Consulte también: