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 
+0

bw.CancellationPending在DoWork開始時永遠不會成立。當你運行「冗長的」代碼時,它只會打開*稍後*。請注意,將CheckForIllegalCrossThreadCalls設置爲False是一個真的,真的,真的是個壞主意。刪除那個。 –

回答

1

在DoWork的情況下,測試CancellationPending內long winded event。 假設這個長過程包含一個for循環或在每個循環測試然後在foreach爲CancellationPending

例如:

Dim worker As BackgroundWorker = CType(sender, BackgroundWorker) 
Dim x as Integer 
For x = 0 to 1000000 
    If worker.CancellationPending = True Then 
     e.Cancel = True 
     Return 
    Else 
     .... ' Execute the works for this loop 
    End If 
Next 

相同的試驗可以在RunWorkerCompleted事件因爲CancelAsync內進行()組CancellationPending屬性的內部值。 See this question查看CancelAsync()的內部工作方式