2017-05-05 13 views
0

forループで10スレッドを開始したVB.NETコンソールプログラムがあります。 ループが終了した後、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 
関連する問題