I am working in VB.Net and I need to pause one thread as it waits for the other to finish.
I've seen a very close question but can't seem to figure it out (And couldn't comment on that post Pause/Resume loop in Background worker)
My scenario is that I have 2 background workers. Worker1 is passing fileNames to Worker2 which processes the files. I need to pause Worker1 if Worker2 hasn't finished. I.e. Worker1 only releases the next fileName after Worker2 has finished
Any ideas on how to do this?
WORKING CODE AFTER COMMENTS FROM @user1666788
Code below is for the scenario stated above of two background workers where one has to wait for the other to finish before proceeding.
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
There you go. Its working as expected. Now need to figure out how to "monitor" progress of writing a file to disk so that I can start off another process after the file has fully been created.....