当 CancelAsync() 调用和 RunWorkerAsync() 调用之间只有非常小的间隔时,我在处理使用 VB.net 停止然后启动后台工作程序时遇到了一些困难。我创建了一个示例来说明以下问题。如果单击一次按钮然后快速连续单击两次,则会出现此示例中的问题。本质上,据我了解,问题在于后台工作人员仍在迭代 for 循环(包括模仿需要一些时间运行的代码),并且还没有机会检查取消是否处于挂起状态。
我尝试使用的解决方案是等待后台工作人员关闭,然后再次启动工作人员。但是,这个 while 循环会无限迭代——后台工作人员永远不会终止。我假设让主线程进入睡眠状态也会让后台工作线程进入睡眠状态。它是否正确?
问题:当检查挂起的取消不能比现在更频繁地进行时,停止后台工作程序然后可能需要在几分之一秒后重新启动它的推荐方法是什么?
建议和意见非常感谢。
Public Class Form1
Dim WithEvents bgWorker As System.ComponentModel.BackgroundWorker = New System.ComponentModel.BackgroundWorker
Friend WithEvents startStopButton As Button = New Button
Dim workerShouldBeRunning As Boolean = False
Sub startStopButton_click() Handles startStopButton.Click
If workerShouldBeRunning Then
bgWorker.CancelAsync()
Else
While bgWorker.IsBusy
Threading.Thread.Sleep(1)
End While
bgWorker.RunWorkerAsync()
End If
workerShouldBeRunning = Not workerShouldBeRunning
End Sub
Sub bgWorker_doWork() Handles bgWorker.DoWork
While Not bgWorker.CancellationPending
Dim sum As Long
For counter = 1 To 100000
sum += counter
Next
Threading.Thread.Sleep(1000)
End While
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
startStopButton.Location = New Point(10, 100)
startStopButton.Size = New System.Drawing.Size(200, 23)
startStopButton.Text = "Click" 'Click to start or stop the background dummy process.
Me.Controls.Add(startStopButton)
bgWorker.WorkerSupportsCancellation = True
End Sub
End Class
编辑:
使用 Ross Presser 的建议,我改进了示例代码。不过,这个解决方案似乎有点糟糕。
Public Class Form1
Dim WithEvents bgWorker As System.ComponentModel.BackgroundWorker = New System.ComponentModel.BackgroundWorker
Friend WithEvents startStopButton As Button = New Button
Dim workerShouldBeRunning As Boolean = False
Dim startQueued As Boolean = False
Sub startStopButton_click() Handles startStopButton.Click
If workerShouldBeRunning Then
bgWorker.CancelAsync()
Else
If bgWorker.IsBusy Then
startQueued = True
Else
bgWorker.RunWorkerAsync()
End If
End If
workerShouldBeRunning = Not workerShouldBeRunning
End Sub
Sub bgWorker_doWork() Handles bgWorker.DoWork
While Not bgWorker.CancellationPending
Dim sum As Long
For counter = 1 To 100000
sum += counter
Next
Threading.Thread.Sleep(1000)
End While
End Sub
Sub bgWorkerCompleted() Handles bgWorker.RunWorkerCompleted
If startQueued Then
startQueued = False
bgWorker.RunWorkerAsync()
End If
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
startStopButton.Location = New Point(10, 100)
startStopButton.Size = New System.Drawing.Size(200, 23)
startStopButton.Text = "Click" 'Click to start or stop the background dummy process.
Me.Controls.Add(startStopButton)
bgWorker.WorkerSupportsCancellation = True
End Sub
End Class