Condividi tramite


BackgroundWorker.DoWork Evento

Definizione

Si verifica quando RunWorkerAsync() viene chiamato .

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 evento

Esempio

Nell'esempio di codice seguente viene illustrato l'uso dell'evento DoWork per avviare un'operazione asincrona. Questo esempio di codice fa parte di un esempio più ampio fornito per la BackgroundWorker classe .

// 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.
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

Commenti

Questo evento viene generato quando si chiama il RunWorkerAsync metodo . In questo caso si avvia l'operazione che esegue il lavoro potenzialmente dispendioso in termini di tempo.

Il codice nel DoWork gestore eventi deve controllare periodicamente il valore della CancellationPending proprietà e interrompere l'operazione se è true. In questo caso, è possibile impostare il Cancel flag di System.ComponentModel.DoWorkEventArgs su truee il Cancelled flag di System.ComponentModel.RunWorkerCompletedEventArgs nel RunWorkerCompleted gestore eventi verrà impostato su true.

Attenzione

Tenere presente che il codice nel gestore eventi potrebbe terminare il lavoro durante l'esecuzione DoWork di una richiesta di annullamento e il ciclo di polling potrebbe non CancellationPending essere impostato su true. In questo caso, il Cancelled flag di System.ComponentModel.RunWorkerCompletedEventArgs nel RunWorkerCompleted gestore eventi non verrà impostato su true, anche se è stata effettuata una richiesta di annullamento. Questa situazione è detta race condition ed è un problema comune nella programmazione multithreading. Per altre informazioni sui problemi di progettazione del multithreading, vedere Procedure consigliate per il threading gestito.

Se l'operazione produce un risultato, è possibile assegnare il risultato alla DoWorkEventArgs.Result proprietà . Sarà disponibile per il RunWorkerCompleted gestore eventi nella RunWorkerCompletedEventArgs.Result proprietà .

Se l'operazione genera un'eccezione che il codice non gestisce, BackgroundWorker rileva l'eccezione e la passa nel RunWorkerCompleted gestore eventi, dove viene esposta come Error proprietà di System.ComponentModel.RunWorkerCompletedEventArgs. Se si esegue nel debugger di Visual Studio, il debugger si interromperà nel punto nel DoWork gestore eventi in cui è stata generata l'eccezione non gestita. Se sono presenti più di un BackgroundWorkeroggetto , non è consigliabile farvi riferimento direttamente, perché in questo modo il DoWork gestore eventi verrà a sua volta a un'istanza specifica di BackgroundWorker. È invece necessario accedere BackgroundWorker eseguendo il cast del sender parametro nel DoWork gestore eventi.

È necessario prestare attenzione a non modificare gli oggetti dell'interfaccia utente nel DoWork gestore eventi. Comunicare invece con l'interfaccia utente tramite gli BackgroundWorker eventi.

Per altre informazioni su come gestire gli eventi, vedere Gestione e generazione di eventi.

Si applica a

Vedi anche