Cenni preliminari sul componente BackgroundWorker

Aggiornamento: novembre 2007

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

Durante l'esecuzione di questo tipo di operazioni è possibile che l'interfaccia utente si blocchi. Nel caso sia necessario eseguire operazioni di questo genere ma si desideri evitare ritardi di risposta dell'interfaccia utente, il componente BackgroundWorker fornisce 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 utilizzato dall'interfaccia utente principale dell'applicazione. Per utilizzare un componente BackgroundWorker, è sufficiente indicare quale metodo di lavoro eseguire in background e quindi chiamare 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 componente BackgroundWorker è disponibile mediante la Casella degli strumenti della scheda Componenti. Per aggiungere un componente BackgroundWorker al form, trascinarlo nel form. Verrà visualizzato nella barra dei componenti e le relative proprietà verranno incluse nella finestra Proprietà.

Per avviare l'operazione asincrona, utilizzare il metodo RunWorkerAsync. Tale metodo richiede un parametro object facoltativo, che può essere utilizzato 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 dell'evento DoWork.

Il gestore dell'evento DoWork accetta un parametro DoWorkEventArgs, che dispone di una proprietà Argument. Tale proprietà riceve il parametro da RunWorkerAsync e può essere passata al metodo di lavoro, che verrà chiamato nel gestore dell'evento DoWork. Nell'esempio riportato di seguito viene illustrato come assegnare un risultato proveniente dal metodo di lavoro ComputeFibonacci. Questo codice fa parte di un esempio più esaustivo fornito in Procedura: implementare un form che utilizza un'operazione in background.

' 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
// 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,
// 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 = (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.set_Result(new Long(ComputeFibonacci(System.Convert.ToInt32
        (e.get_Argument()), worker, e)));
    //e.Result = ComputeFibonacci((int)e.Argument, worker, e); 
} //backgroundWorker1_DoWork

Per ulteriori informazioni sull'utilizzo dei gestori eventi, vedere Eventi e delegati.

Attenzione:

Quando si utilizza qualsiasi tipo di multithreading, si ci espone al rischio di errori gravi e complessi. Consultare Suggerimenti per l'utilizzo del threading gestito prima di implementare soluzioni che utilizzano il multithreading.

Per ulteriori informazioni sull'utilizzo della classe BackgroundWorker, vedere Procedura: eseguire un'operazione in background.

Vedere anche

Attività

Procedura: implementare un form che utilizza un'operazione in background

Altre risorse

Multithreading in Visual Basic