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

我的工作已完成

     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
4

1 回答 1

1

在 DoWork 事件中,测试long winded event. 假设这个长过程包含一个 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 属性的内部值。请参阅此问题以了解 CancelAsync() 的内部工作原理

于 2012-09-01T07:41:33.507 回答