vb.net 后台工作者取消不工作

vb.net background worker cancel not working

我遇到了 BackgroundWorker.CancelAsync() 无法正常工作的问题。我将 WorkerSupportsCancellation 设置为 TRUE。我还在 DoWork 中投票 BackgroundWorker1.CancellationPending。这是我想要实现的示例代码。我让后台工作人员循环遍历时间戳并为 Measurement 变量赋值。我有一个查询最后报告的测量变量并写入列表框的子程序。 5 个循环后,我发送 BackgroundWorker.CancelAsync()。我可以看到取消正在等待,但它实际上并没有取消后台工作人员。这是竞争条件吗?

Public Class Form1

Dim Measurement As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    BackgroundWorker1.RunWorkerAsync()
    Delay(0.5)

    For x = 1 To 5
        ListBox1.Items.Add(Measurement)
        ListBox1.TopIndex = ListBox1.Items.Count - 1
        TextBox1.Text = BackgroundWorker1.CancellationPending
        Delay(1)
    Next

    BackgroundWorker1.CancelAsync()

    TextBox1.Text = BackgroundWorker1.CancellationPending
    ListBox1.Items.Add("Cancel Pend: " & BackgroundWorker1.CancellationPending)
    Delay(5)
    ListBox1.Items.Add("Busy: " & BackgroundWorker1.IsBusy)

End Sub

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    If BackgroundWorker1.CancellationPending = True Then
        e.Cancel = True
        BackgroundWorker1.Dispose()
        Exit Sub
    Else
        Do
            Measurement = Now()
        Loop
    End If

End Sub

结束Class

您只需要将取消检查移到 Do...Loop 中,否则它将仅在 DoWork 事件处理程序开始时进行测试,之后再也不会进行测试

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    If BackgroundWorker1.CancellationPending = True Then
        e.Cancel = True
        BackgroundWorker1.Dispose()
    Else
        Do
          If BackgroundWorker1.CancellationPending = True Then
            e.Cancel = True
            BackgroundWorker1.Dispose()
            Exit Do
          Else 
             Measurement = Now()
          End If
        Loop
    End if
End Sub