Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the C# static constructor thread safe?

In other words, is this Singleton implementation thread safe:

public class Singleton {     private static Singleton instance;      private Singleton() { }      static Singleton()     {         instance = new Singleton();     }      public static Singleton Instance     {         get { return instance; }     } } 
like image 201
urini Avatar asked Aug 10 '08 08:08

urini


People also ask

Is there a C+?

C+ (grade), an academic grade. C++, a programming language. C with Classes, predecessor to the C++ programming language. ANSI C, a programming language (as opposed to K&R C)

What is C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.

public class Singleton {     private static Singleton instance;     // Added a static mutex for synchronising use of instance.     private static System.Threading.Mutex mutex;     private Singleton() { }     static Singleton()     {         instance = new Singleton();         mutex = new System.Threading.Mutex();     }      public static Singleton Acquire()     {         mutex.WaitOne();         return instance;     }      // Each call to Acquire() requires a call to Release()     public static void Release()     {         mutex.ReleaseMutex();     } } 
like image 73
Zooba Avatar answered Sep 18 '22 00:09

Zooba