0
我有一個加載得很好的表單,而且我試圖在加載時使用後臺工作器來觸發一個任務。BackgroundWorker'DoWork'事件沒有觸發
我沒有收到下面的代碼錯誤,但bw.DoWork
事件似乎並沒有被解僱。
我在這裏錯過了什麼嗎?謝謝。
這裏是我的表單類 -
Public Class mainForm
Dim objWorker As MyWorker
Private Sub mainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call Me.loadForm()
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Call Me.closeForm()
End Sub
Private Sub loadForm()
Me.objWorker = New MyWorker ' Invoke the background worker
End Sub
Private Sub closeForm()
Me.objWorker.bw_Cancel() ' Cancel the background worker
Me.Close() ' Close the form
End Sub
End Class
這裏是我的BackgroundWorker類 -
Imports System.ComponentModel
Partial Public Class MyWorker
Private bw As BackgroundWorker = New BackgroundWorker
Public Sub New()
bw.WorkerReportsProgress = False
bw.WorkerSupportsCancellation = True
AddHandler bw.DoWork, AddressOf bw_DoWork
AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
End Sub
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
For i = 1 To 10
If bw.CancellationPending = True Then
e.Cancel = True
Exit For
Else
System.Threading.Thread.Sleep(500)
MsgBox("iteration " & i)
End If
Next
End Sub
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
MsgBox("Complete!")
End Sub
Public Sub bw_Cancel()
If bw.WorkerSupportsCancellation = True Then
bw.CancelAsync()
End If
End Sub
End Class
所有你做的是創造它。您忘記調用RunWorker方法 – Plutonix
缺少對RunWorkerAsync的調用,但請[請檢查此q/a](http://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms -closing-event),當表單關閉時,你可能會遇到運行的BackgroundWorker問題 – Steve
@Steve - 謝謝。現在還不早,但我打算確保在表單關閉時BackgroundWorker不活動。 –