Sunday, February 26, 2012

Thread Safe Singleton Pattern C# .net

There are various different ways for implementing the singleton pattern in C# like locking, double lock checking and with the help of inner class(lazy instantiations) .Here I am discussing one of of them simplest way lazy instantiations that I always preferred because of performance overhead, where you can get the instance from instance property. 
 
Singleton Pattern Implementation
public sealed class threadSafeSingleton{

    private threadSafeSingleton() { }

    public static threadSafeSingleton GetInstance()
    {
        return MyNestedSingletonClass.singleton;
    }

    class MyNestedSingletonClass
    {
        internal static readonly threadSafeSingleton singleton = new threadSafeSingleton();

        static MyNestedSingletonClass() { }
    }
}

Description:
                      Here internal keyword is used to assign the singleton variable, so that other classes can access it. Nested class make it lazy. So in this case if you have more static methods in your class, you can use them without creating the object.

Note: If your multithreaded application requires explicit initialization, you have to take precautions to avoid threading issues.

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Code Imagine