【问题标题】:Background Worker thread not ending on cancellation后台工作线程未在取消时结束
【发布时间】:2012-09-01 07:06:27
【问题描述】:

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

我将发布一些我这样做的示例。

    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

【问题讨论】:

  • bw.CancellationPending 在 DoWork 开始时永远不会为真。只有在您运行“冗长”的代码时,它才会稍后 开启。请注意,将 CheckForIllegalCrossThreadCalls 设置为 False 是一个非常非常非常糟糕的主意。删除那个。

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


【解决方案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() 的内部工作原理

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多