我有我的單身如下:辛格爾頓在當前線程
public class CurrentSingleton
{
private static CurrentSingleton uniqueInstance = null;
private static object syncRoot = new Object();
private CurrentSingleton() { }
public static CurrentSingleton getInstance()
{
if (uniqueInstance == null)
{
lock (syncRoot)
{
if (uniqueInstance == null)
uniqueInstance = new CurrentSingleton();
}
}
return uniqueInstance;
}
}
我想檢查,如果我有兩個線程,會有兩種不同的單身?我想,我有兩個不同的單身人士(具有不同的引用),所以我在做什麼:
class Program
{
static void Main(string[] args)
{
int currentCounter = 0;
for (int i = 0; i < 100; i++)
{
cs1 = null;
cs2 = null;
Thread ct1 = new Thread(cfun1);
Thread ct2 = new Thread(cfun2);
ct1.Start();
ct2.Start();
if (cs1 == cs2) currentCounter++;
}
Console.WriteLine(currentCounter);
Console.Read();
}
static CurrentSingleton cs1;
static CurrentSingleton cs2;
static void cfun1()
{
cs1 = CurrentSingleton.getInstance();
}
static void cfun2()
{
cs2 = CurrentSingleton.getInstance();
}
}
我想,我應該得到currentCounter = 0
(在這種情況下,每兩個單是不同的 - 因爲通過創建其他threrad)。不幸的是,我得到了例如currentCounter = 70
,所以在70例我有同樣的單身人士...你能告訴我爲什麼嗎?
'[ThreadStatic]'可以工作,但請注意,存在奇怪的初始化問題(字段初始值設定項僅適用於訪問的第一個線程),並且沒有乾淨的方法如果需要處理實例,則處理清理。 –
我在變量static CurrentSingleton cs1之前添加了[ThreadStatic];和靜態CurrentSingleton cs2 ;.現在我得到currentCounter = 100,所以在任何情況下,我都有相同的實例...它仍然是錯的 – makcis
@makcis你需要它在CurrentSingleton類中,而不是你設置的變量。 –