Tal*_*ner 1 c# singleton thread-safety
我知道有很多方法可以实现像(双重检查锁定模式,静态只读方法,锁定法)一个线程安全的Singleton模式,但我只是想下面的代码
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; } }
private MyReadOnly()
{
Console.WriteLine((++counter).ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
当我看到这个程序的输出时,我看到只创建了单个对象(因为相同的哈希码)
如何证明此代码不是线程安全的?
编辑
删除静态构造函数会导致一些混淆