-
lock() question
I want to create a Singleton object. On MSDN and other places I found the same example like the one here:
Code:
public sealed class Singleton
{
static Singleton _instance = null;
static readonly object _lock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (_lock)
{
if (_instance==null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
}
It works, that's not the problem. But why is there a seperate object used for locking? Why not just use lock(_instance) instead of lock(_lock)?
-
Re: lock() question
Your question will be answered here.
And creating a singleton can be made easier without using lock.
Code:
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
private Singleton()
{
}
public static Singleton Instance
{
get
{
return _instance;
}
}
}