I have a high-performance Singleton in a multi-threaded environment. Normally I would do something like this:
public static Foo GetInstance()
{
lock (Foo._syncLock)
{
if (Foo._instance == null)
Foo._instance = new Foo();
return Foo._instance;
}
}
I am wondering if the following will be more efficient instead, since it will avoid the continuous blocking of the thread, or is there a hidden problem with it?
public static Foo GetInstance()
{
if (Foo._instance != null)
return Foo._instance;
lock (Foo._syncLock)
{
if (Foo._instance == null)
Foo._instance = new Foo();
return Foo._instance;
}
}
source
share