Friday, July 2, 2010

Multithreaded Singleton in C#

Many a times you run into scenario where only one instance of a class should be created in your application. If you need to know more about Singleton pattern, this article "Singleton pattern" provides good reading. There are quite a few ways to implement this (singleton) but after doing some search on the net found this one to be best for my case.

public sealed class DBHelper {

private static volatile DBHelper instance;
private static object syncRoot = new Object();
private DBHelper() { }

public static DBHelper Instance {
get {
if (instance == null) {
lock (syncRoot) {
if (instance == null)
instance = new DBHelper();
}
}
return instance;
}
}

//more code.....
}

For more information check out Implementing Singleton in C#
This implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created. This ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile  to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot  instance to lock on, rather than locking on the type itself, to avoid deadlocks. This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient.

No comments:

Post a Comment