HighMans HighMans - 6 months ago 90
Vb.net Question

Waiting until threads finish before executing next step

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

NullReferenceException
when I check the values because they haven't been set yet due to the threads still running.

Answer

I would go with the Async / Await pattern on this. It gives you excellent flow control and won't lock up your UI.

Here is a great example from 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 Task also). 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.

Comments