Reputation:
How do I know if a thread is finished when I create it in a loop?
Simplified code:
Public Sub LoadExcelFiles()
AddMore:
Dim t As New Thread(New ThreadStart(AddressOf CreateExcelFile))
t.Start()
'Check if there are more files.
'If yes: GoTo AddMore
End Sub
How do I know when thread 't' is completed? I want to add the file created by 't' into a treeview.
Another problem is, when the user drops 33 files, I have 11 threads running at the same time (3 excelfiles are used per thread)
Upvotes: 0
Views: 76
Reputation:
An interesting article about the answer of @Paul Deen (wish is a good solution) can be found at http://tech.xster.net/tips/multi-threading-in-vb-net/
Tho I did it another way.
Dim t As New Thread(New ThreadStart(AddressOf CreateExcelFile))
If t.IsAlive Then
t.Join()
Else
t.Start()
End If
'Some code here
While t.IsAlive
System.Threading.Thread.Sleep("500")
End While
MessageBox.Show("All Files Completed")
Upvotes: 1
Reputation: 455
You could consider doing it like this:
Delegate Sub CreateExcelFileAsync()
Public Sub LoadExcelFiles()
Dim d As New CreateExcelFileAsync(AddressOf CreateExcelFile)
Dim result As IAsyncResult = d.BeginInvoke(Nothing, Nothing)
'..
'more work
'..
'wait until completed before starting over
If Not result.IsCompleted() Then
result.AsyncWaitHandle.WaitOne()
End If
d.EndInvoke(result)
End Sub
This way you can use the AsyncResult to check the completion.
Upvotes: 1