我在VB.Net工作,我需要暂停一个线程,因为它等待另一个完成。
我看到了一个非常接近的问题,但似乎无法弄明白(并且无法评论该帖子Pause/Resume loop in Background worker)
我的情况是我有2名背景工作者。 Worker1正在将fileNames传递给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
你去吧。它按预期工作。现在需要弄清楚如何“监视”将文件写入磁盘的进度,这样我就可以在文件完全创建后开始另一个进程.....
答案 0 :(得分:1)
我有类似的问题。从我被VS告知的事情来看,它无法完成。 但是我找到了一种绕过子程序的方法,用于暂停/恢复不再使用的线程。
最简单的方法是检查进度,如果它仍在工作,则结束通话。 这是一个例子,假设S1是你的第一个线程,S2是你的第二个。
sub S1()
if(processingfile)then exit sub
'Insert code here for sending next file for processing
end sub
sub S2()
processingfile = true
'Insert code for processing files
processingfile = false
end sub
这或多或少是我解决问题的方法。我希望我的建议有所帮助:)
哦,还有一件事,你可能想要在检查文件是否正在处理之前睡眠第一个线程,这样它就不会耗尽一大堆CPU的功率。但这只是一个猜测,我没有在没有短暂的睡眠期间尝试过它