2015-09-10 45 views
0

我有一个后台工作人员运行循环查询数据库,直到返回一个值。它需要在加载和刷新时启动。上载似乎运行良好,但当我再次调用它失败“BackgroundWorker目前正忙,无法同时运行多个任务”BackgroundWorker当前正忙,无法同时运行多个任务

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

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 

它刷新它必须已经完成,所以我不知道它为什么说它很忙。

+0

后异常的堆栈跟踪。 –

+0

为每个新任务使用新的后台工作人员。听起来你试图重复使用相同的后台工作人员 –

+0

正确,我使用工具栏项目创建了一个。 – asdfasfd

回答

0

您可以通过支持取消来重用该工作人员。将WorkerSupports取消属性设置为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
If (BackgroundWorker1.IsBusy) Then 
    Else 
     BackgroundWorker1.RunWorkerAsync() 
    End If 
+0

这将有助于解释您认为这将解决问题的原因,以及对相关文档或示例的引用。例如,似乎有人质疑BackgroundWorker是否可以重用;一个显示重用的例子会很有帮助。 – matthias

+0

有人错误地将您的答案标记为低质量。您应该添加一些伴随文字来解释您的答案如何工作,以防止进一步标记和/或降价。只有代码答案[不是低质量](https://meta.stackoverflow.com/a/358757/1364007)。它是否试图回答这个问题?如果不是,则标记为“不是答案”或建议删除(如果在审阅队列中)。 b)技术上不正确? Downvote或评论。 [来自评论](https://stackoverflow.com/review/low-quality-posts/18825118)。 –

+0

只需复制[以前的答案]的一部分(// stackoverflow.com/a/32511418)就是抄袭。如果你继续这样做,你会收到禁令。 – robinCTS

相关问题