Search code examples
c#multithreadingstatic-constructor

Making threads in static constructors


In the following example code it appears that the thread that's made in the static constructor only ever gets run after the static constructor finishes executing. In this case that results in the static constructor never finishing because of the wait.

What's going on here?

using System;
using System.Threading;

static public class Test
{
    static public bool isDone = false;

    static Test()
    {
        Thread a = new Thread(TestThread);
        a.Priority = ThreadPriority.Highest;
        a.Start();

        while (!isDone)
            Thread.Sleep(1);

        Console.WriteLine(isDone);
    }

    static private void TestThread()
    {
        isDone = true;
    }
}

Solution

  • EDIT: I was writing non-sense. Static constructors execute under a lock to prevent multiple threads from initializing the static class more than once. However, you try to access your class from multiple threads before this initialization completes, therefore your code results in a deadlock. See explanation here