背景工作者线程没有在取消结束

时间:2012-09-01 07:06:27

标签: vb.net visual-studio-2010 visual-studio backgroundworker

我遇到了一个小问题,我终于想出了如何将一个后台工作者添加到我的应用程序中我现在唯一的问题是它不会结束线程,或者当我点击取消按钮时至少不够快。我一定做错了什么。我希望它在单击按钮后立即中止线程。这可行吗?我的线索绝不是广泛的。

我将发布一些我正在做的方式的例子。

    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

1 个答案:

答案 0 :(得分:1)

在DoWork事件中,在long winded event内测试CancellationPending。 假设这个长过程包含一个For-Loop或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()

的内部工作原理