<p>In other words, is this Singleton implementation thread safe:</p>

<pre><code>public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}
</code></pre>

[{'answer_id': 7104, 'author': 'Dominic Cooney', 'author_id': 878, 'author_profile': 'https://Stackoverflow.com/users/878', 'pm_score': 2, 'selected': False, 'text': '<p>The <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm" rel="nofollow noreferrer">Common Language Infrastructure specification</a> guarantees that "a type initializer shall run exactly once for any given type, unless explicitly called by user code." (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, only one instance of Singleton will be created, and your Instance property is thread-safe.</p>\n\n<p>Note that if Singleton\'s constructor accesses the Instance property (even indirectly) then the Instance property will be null. The best you can do is detect when this happens and throw an exception, by checking that instance is non-null in the property accessor. After your static constructor completes the Instance property will be non-null.</p>\n\n<p>As <a href="https://stackoverflow.com/questions/7095#7105">Zoomba\'s answer</a> points out you will need to make Singleton safe to access from multiple threads, or implement a locking mechanism around using the singleton instance.</p>\n'}, {'answer_id': 7105, 'author': 'Zooba', 'author_id': 891, 'author_profile': 'https://Stackoverflow.com/users/891', 'pm_score': 9, 'selected': True, 'text': '<p>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. <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors</a></p>\n\n<p>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.</p>\n\n<pre><code>public class Singleton\n{\n    private static Singleton instance;\n    // Added a static mutex for synchronising use of instance.\n    private static System.Threading.Mutex mutex;\n    private Singleton() { }\n    static Singleton()\n    {\n        instance = new Singleton();\n        mutex = new System.Threading.Mutex();\n    }\n\n    public static Singleton Acquire()\n    {\n        mutex.WaitOne();\n        return instance;\n    }\n\n    // Each call to Acquire() requires a call to Release()\n    public static void Release()\n    {\n        mutex.ReleaseMutex();\n    }\n}\n</code></pre>\n'}, {'answer_id': 7106, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 5, 'selected': False, 'text': '<p>Using a static constructor actually <em>is</em> threadsafe.  The static constructor is guaranteed to be executed only once.</p>\n\n<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#static-constructors" rel="nofollow noreferrer">From the C# language specification</a>:</p>\n\n<blockquote>\n  <p>The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:</p>\n  \n  <ul>\n  <li>An instance of the class is created.</li>\n  <li>Any of the static members of the class are referenced.</li>\n  </ul>\n</blockquote>\n\n<p>So yes, you can trust that your singleton will be correctly instantiated.</p>\n\n<p>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.</p>\n'}, {'answer_id': 7107, 'author': 'Andrew Peters', 'author_id': 608, 'author_profile': 'https://Stackoverflow.com/users/608', 'pm_score': 3, 'selected': False, 'text': '<p>Static constructors are guaranteed to fire only once per App Domain so your approach should be OK. However, it is functionally no different from the more concise, inline version:</p>\n\n<pre><code>private static readonly Singleton instance = new Singleton();\n</code></pre>\n\n<p>Thread safety is more of an issue when you are lazily initializing things.</p>\n'}, {'answer_id': 7421, 'author': 'Eran Kampf', 'author_id': 1228206, 'author_profile': 'https://Stackoverflow.com/users/1228206', 'pm_score': 1, 'selected': False, 'text': '<p>Static constructor is guaranteed to be thread safe.\nAlso, check out the discussion on Singleton at DeveloperZen:\n<a href="http://web.archive.org/web/20160404231134/http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/" rel="nofollow noreferrer">http://web.archive.org/web/20160404231134/http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/</a></p>\n'}, {'answer_id': 335734, 'author': 'Brian Rudolph', 'author_id': 33114, 'author_profile': 'https://Stackoverflow.com/users/33114', 'pm_score': 7, 'selected': False, 'text': '<p>While all of these answers are giving the same general answer, there is one caveat.  </p>\n\n<p>Remember that all potential derivations of a generic class are compiled as individual types.  So use caution when implementing static constructors for generic types.</p>\n\n<pre><code>class MyObject&lt;T&gt;\n{\n    static MyObject() \n    {\n       //this code will get executed for each T.\n    }\n}\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Here is the demonstration:</p>\n\n<pre><code>static void Main(string[] args)\n{\n    var obj = new Foo&lt;object&gt;();\n    var obj2 = new Foo&lt;string&gt;();\n}\n\npublic class Foo&lt;T&gt;\n{\n    static Foo()\n    {\n         System.Diagnostics.Debug.WriteLine(String.Format("Hit {0}", typeof(T).ToString()));        \n    }\n}\n</code></pre>\n\n<p>In the console:</p>\n\n<pre><code>Hit System.Object\nHit System.String\n</code></pre>\n'}, {'answer_id': 2363090, 'author': 'Florian Doyon', 'author_id': 91585, 'author_profile': 'https://Stackoverflow.com/users/91585', 'pm_score': 2, 'selected': False, 'text': '<p>Just to be pedantic, but there is no such thing as a static constructor, but rather static type initializers, <a href="http://1024strongoxen.blogspot.com/2009/11/there-is-no-such-thing-as-c-static.html" rel="nofollow noreferrer">here\'s a small</a> demo of cyclic static constructor dependency which illustrates this point.</p>\n'}, {'answer_id': 8248031, 'author': 'Jay Juch', 'author_id': 1062600, 'author_profile': 'https://Stackoverflow.com/users/1062600', 'pm_score': 3, 'selected': False, 'text': "<p>Here's the Cliffnotes version from the above MSDN page on c# singleton:</p>\n\n<p>Use the following pattern, always, you can't go wrong:</p>\n\n<pre><code>public sealed class Singleton\n{\n   private static readonly Singleton instance = new Singleton();\n\n   private Singleton(){}\n\n   public static Singleton Instance\n   {\n      get \n      {\n         return instance; \n      }\n   }\n}\n</code></pre>\n\n<p>Beyond the obvious singleton features, it gives you these two things for free (in respect to singleton in c++): </p>\n\n<ol>\n<li>lazy construction (or no construction if it was never called)</li>\n<li>synchronization</li>\n</ol>\n"}, {'answer_id': 22634400, 'author': 'oleksii', 'author_id': 706456, 'author_profile': 'https://Stackoverflow.com/users/706456', 'pm_score': 2, 'selected': False, 'text': '<p>Although other answers are mostly correct, there is yet another caveat with static constructors.</p>\n<p>As per section <em>II.10.5.3.3 Races and deadlocks</em> of the <a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf" rel="nofollow noreferrer">ECMA-335 Common Language\nInfrastructure\n</a></p>\n<blockquote>\n<p>Type initialization alone shall not create a deadlock unless some code\ncalled from a  type initializer (directly or indirectly) explicitly\ninvokes blocking operations.</p>\n</blockquote>\n<p>The following code results in a deadlock</p>\n<pre><code>using System.Threading;\nclass MyClass\n{\n    static void Main() { /* Won’t run... the static constructor deadlocks */  }\n\n    static MyClass()\n    {\n        Thread thread = new Thread(arg =&gt; { });\n        thread.Start();\n        thread.Join();\n    }\n}\n</code></pre>\n<p>Original author is Igor Ostrovsky, see his post <a href="https://devblogs.microsoft.com/pfxteam/static-constructor-deadlocks/" rel="nofollow noreferrer" title="Static constructor deadlocks">here</a>.</p>\n'}, {'answer_id': 41413809, 'author': 'Trade-Ideas Philip', 'author_id': 971955, 'author_profile': 'https://Stackoverflow.com/users/971955', 'pm_score': 3, 'selected': False, 'text': '<p>The static constructor will <strong>finish</strong> running <strong>before</strong> any thread is allowed to access the class.</p>\n\n<pre><code>    private class InitializerTest\n    {\n        static private int _x;\n        static public string Status()\n        {\n            return "_x = " + _x;\n        }\n        static InitializerTest()\n        {\n            System.Diagnostics.Debug.WriteLine("InitializerTest() starting.");\n            _x = 1;\n            Thread.Sleep(3000);\n            _x = 2;\n            System.Diagnostics.Debug.WriteLine("InitializerTest() finished.");\n        }\n    }\n\n    private void ClassInitializerInThread()\n    {\n        System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + ": ClassInitializerInThread() starting.");\n        string status = InitializerTest.Status();\n        System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + ": ClassInitializerInThread() status = " + status);\n    }\n\n    private void classInitializerButton_Click(object sender, EventArgs e)\n    {\n        new Thread(ClassInitializerInThread).Start();\n        new Thread(ClassInitializerInThread).Start();\n        new Thread(ClassInitializerInThread).Start();\n    }\n</code></pre>\n\n<p>The code above produced the results below.</p>\n\n<pre><code>10: ClassInitializerInThread() starting.\n11: ClassInitializerInThread() starting.\n12: ClassInitializerInThread() starting.\nInitializerTest() starting.\nInitializerTest() finished.\n11: ClassInitializerInThread() status = _x = 2\nThe thread 0x2650 has exited with code 0 (0x0).\n10: ClassInitializerInThread() status = _x = 2\nThe thread 0x1f50 has exited with code 0 (0x0).\n12: ClassInitializerInThread() status = _x = 2\nThe thread 0x73c has exited with code 0 (0x0).\n</code></pre>\n\n<p>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.</p>\n'}, {'answer_id': 72322669, 'author': 'binki', 'author_id': 429091, 'author_profile': 'https://Stackoverflow.com/users/429091', 'pm_score': 0, 'selected': False, 'text': '<p>The static constructor is locked. While the type initializer is running, any other thread which attempts to access the class in such a way that would trigger the type initializer will block.</p>\n<p>However, the thread which is running the type initializer can access uninitialized static members. So be sure not to call <code>Monitor.Enter()</code> (<code>lock(){}</code>) or <code>ManualResetEventSlim.Wait()</code> from a type initializer if it is run from a UI thread—those are <a href="https://learn.microsoft.com/en-us/dotnet/standard/threading/managed-and-unmanaged-threading-in-windows#blocking-issues" rel="nofollow noreferrer">“interruptible” waits which result in the event loop running</a>, executing arbitrary other parts of your program while your type initializer is still unfinished.</p>\n<blockquote>\n<p>It is preferable for you to use managed blocking rather than unmanaged blocking. <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitone" rel="nofollow noreferrer"><code>WaitHandle.WaitOne</code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitany" rel="nofollow noreferrer"><code>WaitHandle.WaitAny</code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitall" rel="nofollow noreferrer"><code>WaitHandle.WaitAll</code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor.enter" rel="nofollow noreferrer"><code>Monitor.Enter</code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor.tryenter" rel="nofollow noreferrer"><code>Monitor.TryEnter</code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.join" rel="nofollow noreferrer"><code>Thread.Join</code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.gc.waitforpendingfinalizers" rel="nofollow noreferrer"><code>GC.WaitForPendingFinalizers</code></a>, and so on are all responsive to <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.interrupt" rel="nofollow noreferrer"><code>Thread.Interrupt</code></a> and to <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.abort" rel="nofollow noreferrer"><code>Thread.Abort</code></a>. Also, if your thread is in a single-threaded apartment, all these managed blocking operations will correctly pump messages in your apartment while your thread is blocked:</p>\n</blockquote>\n'}]
['https://Stackoverflow.com/questions/7095', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/373/']