BackgroundWorker.DoWork Evento

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 del evento DoWork 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 la clase BackgroundWorker.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

Comentarios

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

El código del controlador de eventos DoWork debe comprobar periódicamente el valor de la propiedad CancellationPending y anular la operación si se 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 la marca de Cancel de System.ComponentModel.DoWorkEventArgs en truey la marca Cancelled de System.ComponentModel.RunWorkerCompletedEventArgs en el controlador de eventos RunWorkerCompleted 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 del controlador de eventos DoWork puede finalizar su trabajo a medida que se realiza una solicitud de cancelación, y que el bucle de sondeo puede pasar por alto CancellationPending establecerse 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, la marca de Cancelled de System.ComponentModel.RunWorkerCompletedEventArgs en el controlador de eventos de RunWorkerCompleted no se establecerá en true, aunque se haya realizado 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 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 los problemas de diseño de multithreading, vea procedimientos recomendados para el subprocesamiento administrado.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 propiedad DoWorkEventArgs.Result.If your operation produces a result, you can assign the result to the DoWorkEventArgs.Result property. Estará disponible para el controlador de eventos RunWorkerCompleted en la propiedad RunWorkerCompletedEventArgs.Result.This will be available to the RunWorkerCompleted event handler in the RunWorkerCompletedEventArgs.Result property.

Si la operación produce una excepción que el código no controla, el BackgroundWorker detecta la excepción y la pasa al controlador de eventos RunWorkerCompleted, donde se expone como la propiedad Error 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 ejecuta en el depurador de Visual Studio, el depurador se interrumpirá en el punto del controlador de eventos DoWork en el que se produjo 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 un BackgroundWorker, no debe hacer referencia a ninguno de ellos directamente, ya que esto emparejaría su 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 la BackgroundWorker convirtiendo el parámetro sender en el controlador de eventos DoWork.Instead, you should access your BackgroundWorker by casting the sender parameter in your DoWork event handler.

Debe tener cuidado de no manipular ningún objeto de interfaz de usuario en el controlador de eventos de DoWork.You must be careful not to manipulate any user-interface objects in your DoWork event handler. En su lugar, comuníquese con la interfaz de usuario a través de los eventos de BackgroundWorker.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: