Monday, December 23, 2013

C#: Simple singleton blank for everyday use

I have just been writing a specific singleton class and once again, for the umpteenth time, bumped into routine of implementing necessary singleton-related routine. If you are .NET developer who gets bored of doing the same sometimes, saving and sharing the following template with a part of functional ready may save a lot of your time.
public class SingletonClass
{
    //Object which is locked instead of entire instance
    private static object _threadSync = new object();
    //The only instance
    private static volatile SingletonClass _instance = null;
    //Private constructor to lock direct instantiation
    private SingletonClass()
    {
        //Some initial assignments here
    }
    //Instance accessor with double check
    public static SingletonClass Instance
    {
        get
        {
            if (_instance == null) //If instance is not initialized
            {
                lock (_threadSync ) //Lock the sync object
                {
                    if (_instance == null) //And check if other thread has not initialized it
                    {
                        _instance = new SingletonClass(); //If not, perform the initialization
                    }
                }
            }
            return _instance;
        }
    }

    public void SomeAction(Object someData)
    {
        //If the action may be called several times in one moment
        //And uses some concurrent data, it is better to prevent
        //Simultaneous operations with it
        lock (_threadSync)
        {
            //Some actions here
        }
    } 
}

2 comments:

  1. Just FYI http://csharpindepth.com/articles/general/singleton.aspx#lazy

    ReplyDelete