I want to figure out about singleton pattern designs. I want to create seperated instances for per thread from my singleton class. So I provided two designs below.
It is Working
class Program
{
static void Main(string[] args)
{
Task.Factory.StartNew(() => Console.WriteLine(SingletonClass.Instance.GetHashCode()));
Task.Factory.StartNew(() => Console.WriteLine(SingletonClass.Instance.GetHashCode()));
Console.ReadLine();
}
}
public sealed class SingletonClass
{
[ThreadStatic]
private static SingletonClass _instance;
public static SingletonClass Instance
{
get
{
if (_instance == null)
{
_instance = new SingletonClass();
}
return _instance;
}
}
private SingletonClass()
{
}
}
It is not working (Throwing NullReferenceException and instance is not being created.)
class Program
{
static void Main(string[] args)
{
Task.Factory.StartNew(() => Console.WriteLine(SingletonClass.Instance.GetHashCode()));
Task.Factory.StartNew(() => Console.WriteLine(SingletonClass.Instance.GetHashCode()));
Console.ReadLine();
}
}
public sealed class SingletonClass
{
[ThreadStatic]
private static SingletonClass _instance = new SingletonClass();
public static SingletonClass Instance
{
get
{
return _instance;
}
}
private SingletonClass()
{
}
}
I am really wondering why an instance is not created for second design. Can anybody explain that please ?
new
statement to run more than once. – NumerousCodingYoshi
nowhere in the description of singleton does it state it can't be per thread. In other languages ex.D
it would be perfectly normal for it to be per thread. Since everything is thread-local by default there. – Recognition