I think your problem is that you only evaluate CancellationPending once, at the beginning of your bw_DoWork method. Since there really is no way to cancel BackgroundWorker before it starts, CancellationPending will always be false and never interrupt. BackgroundWorker does not use magic to capture the program counter when calling CancelAsync .
For this to work, the main logic of your DoWork method must be implemented in such a way as to provide frequent polling of CancellationPending , so that the code knows exactly when to exit it. You will need to go from this:
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) If bw.CancellationPending = True Then e.Cancel = True Else 'do stuff here End If End Sub
Something like that:
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Dim workIsCompleted As Boolean = False While (Not bw.CancellationPending) AndAlso (Not workIsCompleted) Then ' Do stuff here, but incrementally so that the while loop can ' periodically check to see if CancelAsync has been called. ' Also, be sure to set workIsCompleted = True when the work is done. ' Otherwise, you will just spin forever until someone cancels it ' (Which may or may not be a bad thing, depending on your requirements) End While End Sub
source share