我在VB.Net工作,我需要暂停一个线程,因为它等待另一个完成。暂停和恢复一个线程(后台工作者)
我已经看到了非常密切的问题,但似乎无法推测出来(而不能对后Pause/Resume loop in Background worker评论)
我的情况是,我有2周背景的工人。 Worker1将fileNames传递给处理文件的Worker2。如果Worker2尚未完成,我需要暂停Worker1。即Worker1只在Worker2完成后才释放下一个文件名
有关如何执行此操作的任何想法?
工作代码评论来自@ user1666788下面
代码之后是上述两个背景的工人,其中一个必须等待对方诉讼前完成规定的情形。
Dim isFinished as boolean
Dim currentFiile as integer
Private Sub StartWork_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartWork.Click
bgWorker1.WorkerSupportsCancellation = True
isFinished = True
currentFile = 0
bgWorker1.RunWorkerAsync()
End Sub
Private Sub bgWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker1.DoWork
If isFinished = False Then
bgWorker1.CancelAsync()
End If
isFinished = False
For i = currentFile To fileNames.Count - 1
Dim fileName As String = fileNames(i)
LoadRules(myValidator.GetFileType(fileName))
If i = fileNames.Count Then bgWorker1.CancelAsync()
Exit Sub
Next
End Sub
Private Function LoadRules(ByVal fileType As String) As Boolean
' Function to load some rules for file processing
Try
' Start Thread for actual file processing using bgworker2
bgWorker2.WorkerSupportsCancellation = True
bgWorker2.RunWorkerAsync()
Return True
Catch ex As Exception
End Try
End Function
Private Sub bgWorker2_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker2.DoWork
Try
' Do your thing here
' for x is 0 to 1million
' next
' Mark is finished to true
isFinished = True
' Set currentFile
currentFile += 1
' The bgWorker1 is restarted when bgWorker2 has finished.
' Note however that bgWorker1 will "Continue" where it left off due to the property "currentFile"
bgWorker1.RunWorkerAsync()
'++++++++++++++++++++++++++++++++++++
Catch ex As Exception
End Try
End Sub
你走了。它按预期工作。现在需要弄清楚如何“监视”文件写入磁盘的进度,这样我就可以在文件完全创建后开始另一个进程.....
请向我们显示您的代码。 –
使用有限容量为1的BlockingCollection。 –
@HansPassant根据以下答案中的建议,我已经“快速解决”了我的问题。不过,我已经谷歌搜索BlockingCollection,它看起来像它会以更专业的方式解决上述问题。你有样本实施还是详细指南? – lukik