Ricerca…


Utilizzando BackgroundWorker

Esecuzione di un'attività con l'operatore in background.

Fare doppio clic sul controllo BackgroundWorker dalla casella degli strumenti

BackroundWorker Control in Toolbox

Ecco come appare il BackgroundWorker dopo averlo aggiunto.

inserisci la descrizione dell'immagine qui

Fare doppio clic sul controllo aggiunto per ottenere l'evento BackgroundWorker1_DoWork e aggiungere il codice da eseguire quando viene chiamato BackgroundWorker. Qualcosa come questo:

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    'Do the time consuming background task here

End Sub

La chiamata di BackgroundWorker per eseguire l'attività può essere eseguita in qualsiasi evento come Button_Click , Textbox_TextChanged , ecc. Come segue:

BackgroundWorker1.RunWorkerAsync()

Modificare l'evento RunWorkerCompleted per acquisire l'evento finito dell'attività di BackgroundWorker come segue:

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    MsgBox("Done")
End Sub

Verrà visualizzata una finestra di messaggio che dice Done quando l'operatore termina l'attività assegnata ad esso.

Accesso ai componenti della GUI in BackgroundWorker

Non è possibile accedere a componenti della GUI da BackgroudWorker. Ad esempio se provi a fare qualcosa di simile

Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs)
    TextBox1.Text = "Done"
End Sub

si riceverà un errore di runtime che dice che "Operazione cross-thread non valida: controllo 'TextBox1' accessibile da un thread diverso dal thread su cui è stato creato."

Questo perché BackgroundWorker esegue il codice su un altro thread in parallelo con il thread principale e i componenti della GUI non sono thread-safe. Devi impostare il tuo codice per essere eseguito sul thread principale usando il metodo Invoke , dandogli un delegato:

Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs)
    Me.Invoke(New MethodInvoker(Sub() Me.TextBox1.Text = "Done"))
End Sub

Oppure puoi utilizzare il metodo ReportProgress di BackgroundWorker:

Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs)
    Me.BackgroundWorker1.ReportProgress(0, "Done")
End Sub

Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
    Me.TextBox1.Text = DirectCast(e.UserState, String)
End Sub


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow