Attendere il completamento di BackgroundWorker

Per attendere che un BackgroundWorker termini l’esecuzione asincrona, ad esempio per chiudere una form in modo corretto, il modo più semplice è quello di usare la proprietà Busy e invocare il metodo Application.DoEvents() per non bloccare l’interfaccia utente come indicato in BackgroundWorker.IsBusy Property.

Esempio:

Private Sub FormMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    While Me.backgroundWorker1.IsBusy
        Application.DoEvents()
    End While
End Sub