0
我有一個小問題,我終於想出瞭如何添加一個後臺工作人員到我的應用程序現在我唯一的問題是它不會結束線程,或至少不夠快,當我點擊我的取消按鈕。我一定做錯了什麼。我希望它在點擊按鈕後立即中止線程。這是可行的嗎?我的線程絕不是廣泛的。後臺工作者線程不取消取消
我打算髮表一些我正在做的方式的例子。
Public Sub New()
InitializeComponent()
bw.WorkerReportsProgress = True
bw.WorkerSupportsCancellation = True
AddHandler bw.DoWork, AddressOf bw_DoWork
' AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
End Sub
我的DoWork事件
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
If bw.CancellationPending = True Then
e.Cancel = True
WorkEventRunning = False
Else
CheckForIllegalCrossThreadCalls = False
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
'my long winded event
' more of my long winded event.
End if
我的取消按鈕代碼
Private Sub ToolStripButton2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
'Stop
If bw.WorkerSupportsCancellation = True Then
WorkEventRunning = False
bw.CancelAsync()
bw.Dispose()
End If
而且我WorkCompleted
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
If e.Cancelled = True Then
'canceled
WorkEventRunning = False
ElseIf e.Error IsNot Nothing Then
MsgBox(e.Error.Message)
Else
'done
End If
End Sub
bw.CancellationPending在DoWork開始時永遠不會成立。當你運行「冗長的」代碼時,它只會打開*稍後*。請注意,將CheckForIllegalCrossThreadCalls設置爲False是一個真的,真的,真的是個壞主意。刪除那個。 –