Singleton Instance
I know there are lot of ways to implement a thread safe singleton pattern like (Double Check Locking , static readonly method, lock method) but i just tried below code
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(doSome));
t.Start(null);
}
Console.ReadLine();
}
private static void doSome(object obj)
{
MyReadOnly obj1 = MyReadOnly.getInstance;
Console.WriteLine(obj1.GetHashCode().ToString());
}
class MyReadOnly
{
private static MyReadOnly instance = new MyReadOnly();
int counter = 0;
// static MyReadOnly()
// {
// } treat is as commented code.
public static MyReadOnly getInstance { get { return instance;开发者_如何学JAVA } }
private MyReadOnly()
{
Console.WriteLine((++counter).ToString());
}
}
when i see the output of this program , i see just single object created (because of same hashcode)
how to prove that this code is not thread safe?
EDIT
removing static constructor which causes some confusion
That code is thread-safe due to the nature of type initializers in .NET. The type initializer is guaranteed to run exactly once, and if two threads try to run it at the same time, one will do so and the other will block.
See my article on singleton implementation for more details.
This is actually thread-safe code because you are (indirectly) using static constructor to create the instance (And CLR guarantees invocation of static constructor is thread-safe manner on/before access to any other type member).
精彩评论