静态对象线程安全

时间:2014-05-03 13:31:27

标签: c# multithreading static thread-safety static-members

我有一个预加载的静态xmldocument对象,它有错误代码及其描述, 如果我正在使用多线程应用程序并尝试获取特定错误代码的错误代码描述,我是否需要锁定该方法。

这是我的代码简介(请忽略GetErrorCodeDescription方法的实现,只考虑已使用_oXmlDoc),

预加载的静态xmldocument 的 _oXmlDoc

稍后我调用GetErrorCodeDescription方法来获取这样的错误代码描述,

Public string GetErrorCodeDescription(string errorCode)
{
string errorDEscption="";

    XmlNodeList elemList = **_oXmlDoc**.GetElementsByTagName(errorCode);

    for (int i=0; i < elemList.Count; i++)
    {   
      errorDEscption=elemList[i].InnerXml);
    }  

return errorDEscption;

}

2 个答案:

答案 0 :(得分:0)

最好只对XML进行一次解析,并将所有错误代码和相应的描述放入字典中。如果你使用ConcurrentDictionary,那么你应该是安全的。

答案 1 :(得分:0)

来自the XmlDocument docs;

  

线程安全

     

此类型的任何公共静态(在Visual Basic中为Shared)成员都是线程安全的。 不保证所有实例成员都是线程安全的。

所以,不,如果没有锁定,不能保证使用静态实例是线程安全的。