BackgroundWorker event not firing
Working with BackGroundWorker in my WPF 3.5 application to make a long running process run on its own thread and when I run the code in debug mode in VS2010, the DoWork and the RunWorkerCompleted events do not seem to be firing.
My code is as follows:
Implements INotifyPropertyChanged
Private WithEvents worker As System.ComponentModel.BackgroundWorker
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
Dim worker = New System.ComponentModel.BackgroundWorker
worker.WorkerReportsProgress = True
worker.WorkerSupportsCancellation = True
Dim str() = New String() {"IDA00005.dat", "Adelaide"}
Try
worker.RunWorkerAsync(str)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub worker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles worker.DoWork
Dim form_Helpder As New test_global
Dim ds As DataSet = form_Helpder.getWeatherData(e.Argum开发者_StackOverflow社区ent(0), e.Argument(1))
e.Result = ds
End Sub
Private Sub worker_Completed(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles worker.RunWorkerCompleted
If e.Error IsNot Nothing Then
MsgBox(e.Error.Message)
Else
...
NotifyPropertyChanged("lbl_minToday")
...
End If
End Sub
I have setup breakpoints at runworkerasync and the line is called, not errors are catched but the sub is ended. I have breakpoints also setup on the DoWork and RunWorkerCompleted sub and after the Window_Loaded sub ends, nothing else is highlighted by the debugger, so I am only assuming that the Events are not being fired.
I have two questions, is there anything missing from my code that would make the events not fire, and is the use of breakpoints set on Event subs the correct way of debugging?
Any assistance that can be provided will be greatly appreciated.
Matt
DoWork
and worker_Completed
are events. You have to register them to the worker's event handlers for the worker to fire them.
worker.DoWork += worker_DoWork
worker.RunWorkerCompleted += worker_Completed
Edit: In VB, it looks like the syntax is:
AddHandler worker.DoWork, AddressOf worker_DoWork
AddHandler worker.RunWorkerCompleted, AddressOf worker_Completed
As for your second question, yes, the debugger will break if you set a breakpoint on the worker subroutine. DoWork
runs on a background ThreadPool thread, while RunWorkerCompleted
is raised and runs on the UI thread (which is what makes backgroundWorkers so useful.)
精彩评论