Here is a very simplified example to demonstrate the issue. This works just perfectly:
Dim MyBW As BackgroundWorker Dim bwWorkers As New List(Of BackgroundWorker) Private Sub btnDoSomething_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles btnDoSomething.Click MyBW = New BackgroundWorker Try With MyBW .WorkerReportsProgress = True .WorkerSupportsCancellation = True End With bwWorkers.Add(MyBW) MyBW.RunWorkerAsync() Catch ex As Exception End Try End Sub Private Sub MyBW_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles MyBW.DoWork Stop 'This is just for testing. End Sub
But, If I have several different BackgroundWorkers, and want to reduce coding, I try this way:
Dim bwThis As BackgroundWorker Dim bwThat As Backgroundworker Dim bwWorkers As New List(Of BackgroundWorker) Private Sub DoThis_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles DoThis.Click Dim isOK As Boolean = start_background_worker(bwThis) End Sub Private Sub DoThat_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles DoThat.Click Dim isOK As Boolean = start_background_worker(bwThat) End Sub Private Function start_background_worker(ByRef bw As BackgroundWorker) As Boolean Try bw = New BackgroundWorker With bw .WorkerReportsProgress = True .WorkerSupportsCancellation = True End With bwWorkers.Add(bw) bw.RunWorkerAsync() Return True Catch ex As Exception Return False End Try End Function
Private Sub bwThis_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwThis.DoWork
Stop 'This is just for testing.
End SubPrivate Sub bwThat_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwThat.DoWork
Stop 'This is just for testing.
End Sub
Now I run into the problem. When I click one or the other button to start the job, it doesn't start, and therefore doesn't hit the Stop statement in the DoWork method. If I stop the Background worker, then start it a second time, it then works and hits the Stop statement.
One of the 2 BackgroundWorkers usually starts fine, and the other doesn't, and must be stopped/started again to work. In another application, even the first and only BackgroundWorker has the issue.
Once it is restarted, everything works fine, and all of the BackgroundWorker events work properly.
Any idea what could be causing this? Thanks...
Ron Mittelman