C# Singleton Pattern Designs for ThreadStatic C# Singleton Pattern Designs for ThreadStatic multithreading multithreading

C# Singleton Pattern Designs for ThreadStatic


Instead of using [ThreadStatic] then you could use ThreadLocal<T> which will essentially achieve what you're trying with [ThreadStatic].

public sealed class SingletonClass{    private static ThreadLocal<SingletonClass> _instance;    static SingletonClass()    {        _instance = new ThreadLocal<SingletonClass>(() => new SingletonClass());    }    public static SingletonClass Instance    {        get        {            return _instance.Value;        }    }    private SingletonClass()    {    }}

See: https://msdn.microsoft.com/en-us/library/dd642243(v=vs.110).aspx for more information.

Edit: To answer your question.

In C# when doing:

private static SingletonClass _instance = new SingletonClass();

Regardless if it's marked with [ThreadStatic] or not then it will only create a single static constructor which sets the instance of SingletonClass.

C# does not have the ability to create static constructors per threads.

That's what you can use ThreadLocal<T> for. If we take your code as an example then the default constructor for SingletonClass essentially becomes the "thread-static" constructor.


The answer to your question is mostly related to how class fields are initialized.

In the second example, the _instance field is initialized at declaration. Every time a static field is initialized at declaration, a static constructor will be created (if you don't have it declared already). At compile time, the initialization will be moved into the static constructor. This means that you will end up having something like this (didn't copy the IL code as it would be harder to understand):

public sealed class SingletonClass{    [ThreadStatic]    private static SingletonClass _instance;    public static SingletonClass Instance    {        get        {            return _instance;        }    }    static SingletonClass()    {        _instance = new SingletonClass();    }}

The CLR ensures that the static constructor is called only once, regardless of how many threads you have. Looking at the above code, it means that for the two Tasks that you created, the _instance field will be initialized only once (since there will be only one call to the static constructor).