最近我有一個關於在數百個線程使用的類中使用靜態方法的爭議。 在我看來,「第一」解決方案沒有特別的好處,除了它更容易用於課堂的客戶,但我被告知這是一個非常糟糕的主意,我不得不使用「第二」解決方案。任何人都可以給我清楚的解釋,爲什麼我錯了? 非常感謝!使用靜態方法或實例化類?
PS 讓我們假設字典是線程安全的。
class A
{
static Dictionary<int, string> m_dic = new Dictionary<int, string>();
public static string GetData1(int nKey)
{
return m_dic[nKey];
}
public string GetData2(int nKey)
{
return m_dic[nKey];
}
}
//these func are called from threads...
void ThreadFunc1()
{
print A.GetData1(1);
}
void ThreadFunc2()
{
A a = new A();
print a.GetData2(1);
}
問候, 列昂尼德
>>順便說一句,你認爲它是線程安全的,但你最好確保它是線程安全的。 即時通訊使用線程保存版本 - 所以不要擔心:) – Leonid 2010-07-28 14:46:18