在我的WPF 3.5应用程序中使用BackGroundWorker使一个长时间运行的进程在自己的线程上运行,当我在VS2010中以调试模式运行代码时,DoWork和RunWorkerCompleted事件似乎没有被触发。
我的代码如下:
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.Argument(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
我在runworkerasync上设置断点并调用该行,而不是捕获错误但是sub已经结束。我在DoWork和RunWorkerCompleted子上也设置了断点,在Window_Loaded子结束后,调试器没有突出显示任何其他内容,所以我只假设事件没有被触发。
我有两个问题,我的代码中是否有什么东西会导致事件无法触发,是否使用在Event subs上设置的断点是正确的调试方式?
我们将非常感谢您提供的任何帮助。
马特
答案 0 :(得分:4)
DoWork
和worker_Completed
是事件。您必须将它们注册到工作人员的事件处理程序,以便工人解雇它们。
worker.DoWork += worker_DoWork
worker.RunWorkerCompleted += worker_Completed
编辑:在VB中,语法如下:
AddHandler worker.DoWork, AddressOf worker_DoWork
AddHandler worker.RunWorkerCompleted, AddressOf worker_Completed
关于你的第二个问题,是的,如果在worker子例程上设置断点,调试器将会中断。 DoWork
在后台ThreadPool线程上运行,而RunWorkerCompleted
被引发并在UI线程上运行(这使得backgroundWorkers如此有用。)