Problem Statement is: the lock statement is used in case of implementing the Thread Safe Singleton Pattern.The question is, we need to lock a resource but using a lock(x){} statement is bit expensive as per the interviewer. What is the most efficient or optimum way to lock a resource without using lock statement?
Is there any catch or trick in this question?
one way to implement thread safe single is via use of static.
public sealed class Singleton{ private static readonly Singleton obj = new Singleton(); public static Singleton Obj { get { return obj; } }
public sealed class Singleton{ private static readonly Singleton obj = new Singleton(); public static Singleton Obj { get { return obj; } } private Singleton() {}}
public sealed class Singleton
{
private static readonly Singleton obj = new Singleton();
public static Singleton Obj
get
return obj;
}
private Singleton() {}
To access the instance of Singleton Class:Singleton mySingleton = Singleton.Obj;