Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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
}
}
}


This post first appeared on Ilya Tereschuk, please read the originial post: here

Share the post

C#: Simple singleton blank for everyday use

×

Subscribe to Ilya Tereschuk

Get updates delivered right to your inbox!

Thank you for your subscription

×