C # - Singleton Template

As you can see from my nickname, I'm a newbie actually found out about the Singleton template, where I had one problem. Before I find out that static constructors always execute before standard constructors, but in the code below the result is different, first I see the string "Insta" and then "Static", why is this happening?

sealed class Singleton { private static readonly Singleton instance; private Singleton() { Console.WriteLine("Insta"); } static Singleton() { instance = new Singleton(); Console.WriteLine("Static"); } public static Singleton Instance { get { return instance; } } } class Program { static void Main() { Singleton s1 = Singleton.Instance; } } 
+7
constructor c # static singleton
source share
3 answers

If you write

 static Singleton() { Console.WriteLine("Static"); //THIS COMES FIRST instance = new Singleton(); } 

you will see what you expect

static ctor executes first, as expected, but you print to the console after instance = new Singleton(); but this line executes the ctor instance, so "inst".

So, the thread of execution:

  • static ctor
    • instance = new Singleton();
      • ctor instance prints "insta"
    • "static"
+13
source share

See the MSDN pattern here for a qualitative explanation of the singleton pattern.

MSDN recommends you write it below to be thread safe:

 using System; public sealed class Singleton { private static volatile Singleton instance; private static object syncRoot = new Object(); private Singleton() {} public static Singleton Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new Singleton(); } } return instance; } } } 

By the way, this template has the following advantages over the static constructor:

Creating an instance is not performed until the object requests an instance; this approach is called a lazy instance. Lazy instance allows you to avoid creating unnecessary singles when you run the application.

Make sure that it meets your needs, and if so, implement this solution.

+8
source share

The static method starts first. Here's the proof - change the code to the following:

 static Singleton() { Console.WriteLine("Static method start"); instance = new Singleton(); Console.WriteLine("Static method end"); } 
+1
source share

All Articles