Goroutines in Visual Basic .NET

Goroutines

A goroutine is a lightweight thread of execution.

Imports System
Imports System.Threading

Module Program
    Sub Main(args As String())
        ' Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.
        f("direct")

        ' To invoke this function in a separate thread, use a Thread. This new thread will execute concurrently with the calling one.
        Dim thread As New Thread(Sub() f("thread"))
        thread.Start()

        ' You can also start a thread for an anonymous function call.
        Dim threadAnon As New Thread(Sub(msg As String) Console.WriteLine(msg))
        threadAnon.Start("going")

        ' Our two function calls are running asynchronously in separate threads now. Wait for them to finish.
        Thread.Sleep(1000)
        Console.WriteLine("done")
    End Sub

    Sub f(from As String)
        For i As Integer = 0 To 2
            Console.WriteLine($"{from} : {i}")
        Next
    End Sub
End Module

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct")

To invoke this function in a separate thread, use a Thread. This new thread will execute concurrently with the calling one.

Dim thread As New Thread(Sub() f("thread"))
thread.Start()

You can also start a thread for an anonymous function call.

Dim threadAnon As New Thread(Sub(msg As String) Console.WriteLine(msg))
threadAnon.Start("going")

Our two function calls are running asynchronously in separate threads now. Wait for them to finish.

Thread.Sleep(1000)
Console.WriteLine("done")

When we run this program, we see the output of the blocking call first, then the output of the two threads. The threads’ output may be interleaved because threads are being run concurrently by the .NET runtime.

direct : 0
direct : 1
direct : 2
thread : 0
going
thread : 1
thread : 2
done

Next we’ll look at a complement to threads in concurrent .NET programs: tasks.