1

我在 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

你去吧。它按预期工作。现在需要弄清楚如何“监控”将文件写入磁盘的进度,以便在文件完全创建后我可以启动另一个进程.....

4

1 回答 1

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

这或多或少是我解决这个问题的方式。我希望我的建议有所帮助:)

Oh and one more thing, you might want to sleep the first thread before checking if the file is processing so that it doesn't use up a bunch of CPU power. But that's just a guess, I haven't tried it without a short sleeping period

于 2012-09-18T21:25:49.550 回答