2011-01-14 50 views
1

在我的WPF 3.5應用程序中使用BackGroundWorker來使自己的線程運行一個長時間運行的進程,並且當我在VS2010中以調試模式運行代碼時,DoWork和RunWorkerCompleted事件似乎沒有觸發。BackgroundWorker事件未觸發

我的代碼如下:

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設置斷點和行調用,而不是錯誤,但逮住分結束。我還在DoWork和RunWorkerCompleted子節點上設置了斷點,並且在Window_Loaded子節點結束之後,調試器沒有突出顯示任何其他內容,因此我只假設事件未被觸發。

我有兩個問題,有沒有什麼東西從我的代碼中丟失,會導致事件不能觸發,並且使用Event Sub上設置的斷點調試的正確方式?

任何可以提供的援助將不勝感激。

馬特

回答

4

DoWorkworker_Completed的事件。您必須將它們註冊到工作人員的事件處理程序中,以供工作人員解除它們。

worker.DoWork += worker_DoWork 
worker.RunWorkerCompleted += worker_Completed 

編輯:在VB中,它看起來像語法是:

AddHandler worker.DoWork, AddressOf worker_DoWork 
AddHandler worker.RunWorkerCompleted, AddressOf worker_Completed 

關於你的第二個問題,是的,調試器將如果設置在工人子程序斷點打破。 DoWork在背景ThreadPool線程上運行,而RunWorkerCompleted被引發並在UI線程上運行(這使得backgroundWorkers如此有用。)

+0

太好了,我以前見過C#版本,但是我無法讓它工作,所以只是計算這是一個C#的東西。添加這兩行工作,非常感謝您的幫助。 – Lima 2011-01-14 21:45:28