vb.net 后台工作线程取消不起作用



我遇到了BackgroundWorker.CancelAsync()无法正常工作的问题。我已将工作人员支持取消设置为 TRUE。我也在DoWork中轮询BackgroundWorker1.CancelEnding。这是我试图实现的示例代码。我让后台工作线程循环访问时间戳并为 Measurement 变量分配一个值。我有一个子例程,用于查询上次报告的 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

结束类

您只需要在 Do...循环,否则将仅在 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

最新更新