最近我有一个关于在数百个线程使用的类中使用静态方法的争议。 在我看来,“第一”解决方案没有特别的好处,除了它更容易用于课堂的客户,但我被告知这是一个非常糟糕的主意,我不得不使用“第二”解决方案。任何人都可以给我清楚的解释,为什么我错了? 非常感谢!使用静态方法或实例化类?
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