简体   繁体   中英

Threadsafe Static Class and Constructor

Is static class constructor by default threadsafe ? Or it need to explictely make threadsafe?

The CLR guarantees that the static constructor will be invoked only once for the entire lifetime of the AppDomain. It will be called the first time a static member is accessed or an instance is created. And since it is called only once per AppDomain you could safely assume that only a single thread can call it.

If by thread-safe, you mean "Will it only be called once?", then the answer is yes. However, the CLR does this by taking a global lock to prevent multiple threads from calling the static constructor. This means that if you do something that will cause another thread to try and get that lock (eg by invoking a static method on the class) then there is the possibility of a deadlock.

For example, the following program deadlocks (from Eric Lippert but I can't seem to find a reference):

public class Program
{
    static Program()
    {
        Thread thread = new Thread(Test);
        thread.Start();
        thread.Join();
    }

    public static void Main(string[] args)
    {
        Console.WriteLine("Hello, world!");
    }

    static void Test() { }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM