我在 VB.Net 中工作,我需要暂停一个线程,因为它等待另一个线程完成。
我已经看到了一个非常接近的问题,但似乎无法弄清楚(并且无法评论后台工作人员中的 Pause/Resume loop帖子)
我的情况是我有 2 个后台工作人员。Worker1 将文件名传递给处理文件的 Worker2。如果 Worker2 还没有完成,我需要暂停 Worker1。即Worker1只有在Worker2完成后才释放下一个fileName
关于如何做到这一点的任何想法?
来自@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
你去吧。它按预期工作。现在需要弄清楚如何“监控”将文件写入磁盘的进度,以便在文件完全创建后我可以启动另一个进程.....