Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 在循环中创建线程,并等待所有线程完成/中止_Vb.net - Fatal编程技术网

Vb.net 在循环中创建线程,并等待所有线程完成/中止

Vb.net 在循环中创建线程,并等待所有线程完成/中止,vb.net,Vb.net,我有一个VB.NET控制台程序,其中我在for循环中启动了10个线程。 循环完成后,10个线程将运行,我需要代码在for循环完成后立即暂停,直到所有线程完成/中止 我怎么做 以下是一个例子: Private Sub TheProcessThread() While True 'some coding If 1 = 1 Then End If End While Console.WriteLine("Aborting

我有一个VB.NET控制台程序,其中我在for循环中启动了10个线程。 循环完成后,10个线程将运行,我需要代码在for循环完成后立即暂停,直到所有线程完成/中止

我怎么做

以下是一个例子:

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

这应该会有所帮助。我对你的代码做了一些修改,但本质上是一样的

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

保持简单和老派,只需像这样使用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

请不要调用Thread.CurrentThread.Abort,除非您试图强制关闭应用程序。调用.Abort会使.NET运行时处于无效状态。