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; }
}
}
While all of these answers are giving the same general answer, there is one caveat.
Remember that all potential derivations of a generic class are compiled as individual types. So use caution when implementing static constructors for generic types.
EDIT:
Here is the demonstration:
In the console:
The static constructor will finish running before any thread is allowed to access the class.
The code above produced the results below.
Even though the static constructor took a long time to run, the other threads stopped and waited. All threads read the value of _x set at the bottom of the static constructor.
Using a static constructor actually is threadsafe. The static constructor is guaranteed to be executed only once.
From the C# language specification http://msdn.microsoft.com/en-us/library/aa645612(VS.71).aspx:
So yes, you can trust that your singleton will be correctly instantiated.
Zooba made an excellent point (and 15 seconds before me, too!) that the static constructor will not guarantee thread-safe shared access to the singleton. That will need to be handled in another manner.
Static constructor is guaranteed to be thread safe. Also, check out the discussion on Singleton at DeveloperZen: http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/