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;
public event System.ComponentModel.DoWorkEventHandler? DoWork;
member this.DoWork : System.ComponentModel.DoWorkEventHandler 
Public Custom Event DoWork As DoWorkEventHandler 

Tipo de evento

DoWorkEventHandler

Ejemplos

En el ejemplo de código siguiente se muestra el uso del 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 la 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

Comentarios

Este evento se genera cuando se llama al RunWorkerAsync método.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 DoWork controlador de eventos debe comprobar periódicamente el CancellationPending valor de la 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 la Cancel marca de System.ComponentModel.DoWorkEventArgs en true y la Cancelled marca de System.ComponentModel.RunWorkerCompletedEventArgs en el controlador de RunWorkerCompleted 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 del DoWork controlador de eventos puede finalizar su trabajo a medida que se realiza una solicitud de cancelación y que es posible que el bucle de sondeo no CancellationPending se establezca 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 Cancelled marca de System.ComponentModel.RunWorkerCompletedEventArgs en el 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 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 DoWorkEventArgs.Result propiedad.If your operation produces a result, you can assign the result to the DoWorkEventArgs.Result property. Estará disponible para el RunWorkerCompleted controlador de eventos en la RunWorkerCompletedEventArgs.Result propiedad.This will be available to the RunWorkerCompleted event handler in the RunWorkerCompletedEventArgs.Result property.

Si la operación genera una excepción que el código no controla, BackgroundWorker detecta la excepción y la pasa al 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 ejecuta en el depurador de Visual Studio, el depurador se interrumpirá en el punto del controlador de eventos en el DoWork 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 uno 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 su BackgroundWorker mediante la conversión del sender parámetro en el DoWork controlador de eventos.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 DoWork controlador de eventos.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 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