vb.net 在执行下一步之前等待线程完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37616365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Waiting until threads finish before executing next step
提问by Bradley Uffner
I, at most, have two threads running at any single time. How do I wait for these threads to finish before executing my next step?
我最多同时运行两个线程。如何在执行下一步之前等待这些线程完成?
If I don't wait for them, I get a NullReferenceExceptionwhen I check the values because they haven't been set yet due to the threads still running.
如果我不等待它们,我会NullReferenceException在检查值时得到一个,因为由于线程仍在运行,它们尚未设置。
回答by Bradley Uffner
I would go with the Async / Await pattern on this. It gives you excellent flow control and won't lock up your UI.
我会在这方面使用 Async / Await 模式。它为您提供了出色的流程控制,并且不会锁定您的 UI。
Here is a great example from MSDN:
这是来自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
The basic idea is to create an array of Task(these can point to functions that return Taskalso). This queues up the "threads" wrapped in task objects that get run when you call Task.WhenAll, which will execute all the tasks in the array and continue after they all complete. Code after that will run once every tasks completes, but it won't block the UI thread.
基本思想是创建一个数组Task(这些可以指向也返回的函数Task)。这Task.WhenAll会将包含在任务对象中的“线程”排队,当您调用时,这些任务对象会运行,这将执行数组中的所有任务并在它们全部完成后继续。之后的代码将在每个任务完成后运行,但不会阻塞 UI 线程。
回答by ruirodrigues1971
If you call join the main Thread will be wait that the other thread finished. I think the code bellow will be good to understand the idea.
如果您调用 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

