Leo*_*nid 1 c# static multithreading
最近我在一个由数百个线程使用的类中使用静态方法时遇到了争议.在我看来,"第一"解决方案没有特别的好处,除了它更容易用于课堂的客户,但我被告知这是非常糟糕的主意,我必须使用"第二"解决方案.谁能给我清楚解释为什么我这么错?非常感谢!
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);
}
Run Code Online (Sandbox Code Playgroud)
此致,列昂尼德
使用实例成员意味着(至少对我来说)实例本身有一些相关的东西 - 它的状态,或者可能是它在重写方法方面的行为(即"状态"是实例的执行时类型) .
在这种情况下,这些都不是真的 - 所以我会将实例视为坏样式,导致误导代码.
| 归档时间: |
|
| 查看次数: |
800 次 |
| 最近记录: |