我有一个小问题,我终于想出了如何向我的应用程序添加后台工作程序,现在我唯一的问题是它没有结束线程,或者至少在我单击取消按钮时速度不够快。我一定做错了什么。我希望它在单击按钮后立即中止线程。这可行吗?我的主题绝不是广泛的。
我将发布一些我正在做的事情的例子。
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
我的工作已完成
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