Cenni preliminari sul componente BackgroundWorker

Molte operazioni comuni hanno tempi di esecuzione particolarmente lunghi, Ad esempio:

  • Download di immagini

  • Chiamate di servizi Web

  • Download e caricamento di file (anche per applicazioni peer-to-peer)

  • Calcoli locali complessi

  • Transazioni di database

  • Accesso locale ai dischi, a causa della velocità ridotta rispetto all'accesso alla memoria

Le operazioni come queste possono causare il blocco dell'interfaccia utente durante l'esecuzione. Nel caso sia necessario eseguire operazioni di questo genere ma si vogliano evitare ritardi di risposta dell'interfaccia utente, il componente BackgroundWorker costituisce la soluzione ideale.

Il componente BackgroundWorker offre la possibilità di eseguire operazioni che richiedono molto tempo in modo asincrono (in background) su un thread diverso da quello usato dall'interfaccia utente principale dell'applicazione. Per usare un componente BackgroundWorker, è sufficiente indicare il metodo di lavoro da eseguire in background e quindi chiamare il metodo RunWorkerAsync. Il thread chiamante continua l'esecuzione normale mentre il metodo di lavoro viene eseguito in modo asincrono. Al completamento dell'esecuzione del metodo, il componente BackgroundWorker avvisa il thread chiamante attivando l'evento RunWorkerCompleted, in cui è possibile includere i risultati dell'operazione.

Il BackgroundWorker componente è disponibile nella casella degli strumenti nella scheda Componenti . Per aggiungere un oggetto BackgroundWorker al form, trascinare il BackgroundWorker componente nel form. Viene visualizzato nella barra dei componenti e le relative proprietà vengono visualizzate nella finestra Proprietà .

Per avviare l'operazione asincrona, usare il metodo RunWorkerAsync. Il metodo RunWorkerAsync accetta un parametro object facoltativo, che può essere usato per passare gli argomenti al metodo di lavoro. La classe BackgroundWorker espone l'evento DoWork a cui viene collegato il thread di lavoro mediante un gestore eventi DoWork.

Il gestore eventi DoWork accetta un parametro DoWorkEventArgs che include una proprietà Argument. Questa proprietà riceve il parametro da RunWorkerAsync e può essere passata al metodo di lavoro, che verrà chiamato nel gestore eventi DoWork. L'esempio seguente illustra come assegnare un risultato proveniente da un metodo di lavoro denominato ComputeFibonacci. Fa parte di un esempio più ampio, disponibile in Procedura: Implementare un modulo che usa un'operazione in background.

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

Per altre informazioni sull'uso dei gestori eventi, vedere Eventi.

Attenzione

L'uso di qualsiasi tipo di multithreading determina la potenziale esposizione a bug seri e complessi. Vedere Procedure consigliate per l'uso del threading gestito prima di implementare soluzioni che usano il multithreading.

Per altre informazioni sull'uso della BackgroundWorker classe , vedere Procedura: Eseguire un'operazione in background.

Vedi anche