BackgroundWorker当前很忙,无法同时运行多个任务

时间:2015-09-10 14:36:08

标签: vb.net

我有一个后台工作程序来运行查询数据库的循环,直到返回一个值。它需要在加载和刷新时启动。负载似乎运行正常,但是当我再次调用它时,“BackgroundWorker当前正忙,并且不能同时运行多个任务”

我将backgroundworker添加到我的表单中,添加了它需要对doWork事件做的工作。

   Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgwProcessResource.DoWork
        Logic.SetConnection(connectionString)
        materialConfirmed = False
        Dim sqlManager As New BOMIDatabaseManager(connectionString)
        Dim currentInstance As New ResourceInstance(resource, instance)
        Dim results As New Hashtable
        status = Logic.ProcessResource(currentInstance)
        While status.woID.Count <= 0
            status = Logic.ProcessResource(currentInstance)
        End While
        currentWO = status.woID(0)
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwProcessResource.RunWorkerCompleted
        WaitingForm.Close()
        'Me.Enabled = False
        currentWO = status.woID(0)
        controller.SelectWorkOrder(status.woID(0), "20")
    End Sub

为了刷新它必须已经完成所以我不确定为什么它说它很忙。

2 个答案:

答案 0 :(得分:1)

您可以通过支持取消来重复使用该工作人员。在设计器中或通过代码将 WorkerSupportsCancellation 属性设置为 True

BackgroundWorker1.WorkerSupportsCancellation = True

在刷新按钮中,检查工作人员当前是否正忙,如果是,则取消该任务。

If (BackgroundWorker1.IsBusy) Then
    BackgroundWorker1.CancelAsync()

    ' Spin up another thread to wait 2 seconds and allow the
    ' background worker to stop so that you can start it.
    ' If you don't want to do this, do something else to allow time to pass
    Dim myTask As New Task(Sub()
                                Threading.Thread.Sleep(2000)
                            End Sub)

    myTask.ContinueWith((Sub() BackgroundWorker1.RunWorkerAsync()))

    myTask.Start()

Else

    BackgroundWorker1.RunWorkerAsync()

End If

这意味着上面的代码需要查找取消和处理停止工作

While status.woID.Count <= 0
    If (BackgroundWorker1.CancellationPending) Then
        Exit While
    End If

    status = Logic.ProcessResource(currentInstance)
End While

答案 1 :(得分:-2)

    If (BackgroundWorker1.IsBusy) Then
    Else
        BackgroundWorker1.RunWorkerAsync()
    End If