在执行下一步之前等待线程完成

时间:2016-06-03 13:58:42

标签: vb.net multithreading winforms

我最多只能在任何一次运行两个线程。在执行下一步之前,如何等待这些线程完成?

如果我不等他们,我检查值时会得到一个NullReferenceException,因为线程仍在运行,因为它们尚未设置。

2 个答案:

答案 0 :(得分:7)

我会选择Async / Await模式。它为您提供出色的流量控制,并且不会锁定您的UI。

以下是MSDN的一个很好的例子:

Public Class Form1
    Public Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim tasks As New List(Of Task)()
        tasks.Add(Task.Run(addressof Task1))
        tasks.Add(Task.Run(addressof Task2))
        Await Task.WhenAll(tasks)

        MsgBox("Done!")
    End Sub

    Private Async Function Task1() As Task 'Takes 5 seconds to complete
        'Do some long running operating here. Task.Delay simulates the work, don't use it in your real code
        Await Task.Delay(5000)
    End Function

    Private Async Function Task2() As Task 'Takes 10 seconds to complete
        'Do some long running operating here. Task.Delay simulates the work, don't use it in your real code
        Await Task.Delay(10000)
    End Function
End Class

基本思想是创建一个Task数组(这些数组也可以指向返回Task的函数)。这会排队"线程"包含在调用Task.WhenAll时运行的任务对象中,这将执行数组中的所有任务并在完成后继续。之后的代码将在每个任务完成后运行一次,但它不会阻止UI线程。

答案 1 :(得分:0)

如果你调用join主线程将等待另一个线程完成。我认为下面的代码很好理解这个想法。

Sub Main()
        thread = New System.Threading.Thread(AddressOf countup)
        thread.Start()
        thread2 = New System.Threading.Thread(AddressOf countup2)
        thread2.Start()
        thread.Join() 'wait thread to finish
        thread2.Join()  'wait thread2 to finish
        Console.WriteLine("All finished ")
        Console.ReadKey()
    End Sub

查看链接: General; WinForms