Goroutines in C#

A goroutine is a lightweight thread of execution.

using System;
using System.Threading;

class Program
{
    static void f(string from)
    {
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine($"{from} : {i}");
        }
    }

    static void Main(string[] args)
    {
        // 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 goroutine, use
        // a new Thread. This new thread will execute
        // concurrently with the calling one.
        
        Thread thread = new Thread(() => f("goroutine"));
        thread.Start();
        
        // You can also start a thread for an anonymous
        // function call.
        
        Thread thread2 = new Thread(() => Console.WriteLine("going"));
        thread2.Start();

        // Our two function calls are running asynchronously in
        // separate threads now. Wait for them to finish
        // (for a more robust approach, use a ManualResetEvent).
        
        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.

$ dotnet run
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

Next we’ll look at a complement to threads in concurrent C# programs: Tasks.