Answer: public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
In the above code, when the Singleton instance is created for the first time then it is locked and synchronized but next call or successive calls make sure that the lock is not checked anymore because an instance already exists. This way the overhead of checking the lock minimizes.
The double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method.
Thanks and Regards
Akiii
Source: MSDN | Asked In: Some Interviews |
Alert Moderator