2017-05-05 95 views
0

我有一個VB.NET控制檯程序,其中我在for循環中啓動了10個線程。 循環完成後,10個線程將運行,我需要代碼暫停(在完成for-loop之後),直到所有線程完成/中止爲止。在循環中創建線程並等待所有線程完成/中止

我該怎麼辦?

這裏是例子:

Private Sub TheProcessThread() 

    While True 

     'some coding 
     If 1 = 1 Then 

     End If 

    End While 

    Console.WriteLine("Aborting Thread...") 
    Thread.CurrentThread.Abort() 

End Sub 

Sub Main() 

    Dim f as Integer 
    Dim t As Thread 
    For f = 0 To 10 
     t = New Thread(AddressOf TheProcessThread) 
     t.Start() 
    Next 

    ' HERE !! how I can be sure that all threads are finished/aborted for continue with the code below ? 
    ' more vb.net code... 
End Sub 
+0

請不要永遠永遠永遠調用'Thread.CurrentThread.Abort()'** **除非你是試圖強行關閉你的應用程序。調用'.Abort()'可以使.NET運行時處於無效狀態。 – Enigmativity

回答

0

這應該幫助。我對代碼做了一些修改,但實質上是一樣的。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim f As Integer 
    Dim t As Task 
    Dim l As New List(Of Task) 
    For f = 0 To 10 
     t = New Task(AddressOf TheProcessThread) 
     t.Start() 
     l.Add(t) 
    Next 

    ' HERE !! how I can be sure that all threads are finished/aborted for continue with the code below ? 
    ' more vb.net code... End Sub 
    Task.WaitAll(l.ToArray) 'wait for all threads to complete 
    Stop 
End Sub 

Private Sub TheProcessThread() 

    While True 

     'some coding 
     If 1 = 1 Then 
      Threading.Thread.Sleep(1000) 
      Exit While 
     End If 

    End While 

    Console.WriteLine("Aborting Thread...") 
    'Thread.CurrentThread.Abort() 'End Sub causes thread to end 

End Sub 
0

保持簡單和老派,只是用Join()這樣的:

Imports System.Threading 

Module Module1 

    Private R As New Random 

    Sub Main() 
     Dim threads As New List(Of Thread) 
     For f As Integer = 0 To 10 
      Dim t As New Thread(AddressOf TheProcessThread) 
      threads.Add(t) 
      t.Start() 
     Next 
     Console.WriteLine("Waiting...") 
     For Each t As Thread In threads 
      t.Join() 
     Next 

     Console.WriteLine("Done!") 
     Console.ReadLine() 
    End Sub 

    Private Sub TheProcessThread() 
     Thread.Sleep(R.Next(3000, 10001)) 
     Console.WriteLine("Thread Complete.") 
    End Sub 

End Module