Singleton and Thread Safe Methods on .Net


Recently I had a code review on one of my colleagues project and found this common implementation there:

public sealed class TheClass {
   private TheClass() {}
   private static _theClass value;
   private static object obj = new Object();
    public static Instance Value {
          get {
                 if (TheClass.value == null) {
                        lock (syncRoot) {
                               if (TheClass.value == null) {
                                      TheClass.value = new TheClass();
                 return TheClass.value;

Yes we are talking about the classic Singleton pattern here, but not implemented as the proper or, more importantly, safer way. This implementation could permit a double instantation at some point. In short I’ll just recommend to make _theClass volatile, but I know it’s not the unique way to achieve this and is not always the safer way in all platforms. So searching this on the internet I found a lot of discussions so if you are interested on a deep level reading check this links:

volatile and MemoryBarriers
Double-checked locking in .net at Stackoverflow

Alois Kraus even shows the assembled code!
Lazy Vs Eager Init Singletons / Double-Check Lock Pattern

And of course the Official Microsoft Pattern

Good reading!


One thought on “Singleton and Thread Safe Methods on .Net

  1. Pingback: El Patrón Singleton y los métodos “Thread Safe” en .Net « Ernesto Ocampo Blog en Español

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s