Monday, December 28, 2009

Different ways to Implement the Singleton in .NET

Lots of blogs and sites are talking about the ways to implement the singleton in different ways; and surprisingly many of them some times miss the thread safety or the thread sync. According to the "Design Patterns: Elements of Reusable Object-Oriented Software" the implementation of Singleton should be as follow:

The above implementation may work well considering that singleton implementation can be breakable at the first call. In "GetInstance" method we are checking "instance == null" which returns true when 2 requests comes at the same time at the first call. Plus we are not taking the advantage of the .NET language features. Here is the thread safe implementation of Singleton in .NET C# language.

Here you need to watch the usage of volatile (One can consider the implementation of "volatile" exactly opposite of "ThreadStatic" keyword) and static keyword gives the grantee to be thread safe in .NET compilation. (According to Jeffrey Richter).