简体   繁体   English

静态对象线程安全

[英]Static object thread safety

I have a pre-loaded static xmldocument object which has errorcode and it descriptions, If i am using multi threaded application and trying to get a error code description for particular error code, Do i need to put a lock on that method or not. 我有一个预加载的静态xmldocument对象,该对象具有错误代码及其描述,如果我使用多线程应用程序并尝试获取特定错误代码的错误代码描述,是否需要对该方法进行锁定。

Here is my code in brief (Pls. ignore the implementation of GetErrorCodeDescription method, Only consider that _oXmlDoc has been used ), 这是我的简短代码(请忽略GetErrorCodeDescription方法的实现,仅考虑已使用_oXmlDoc),

Pre-loaded static xmldocument _oXmlDoc 预加载的静态xmldocument _oXmlDoc

later i am calling GetErrorCodeDescription method to get an error code description like this , 稍后我调用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;

}

You would be better off doing this parsing of XML just once and putting all error codes and corresponding descriptions into a dictionary. 您最好只进行一次XML解析,然后将所有错误代码和相应的描述放入字典中。 If you use ConcurrentDictionary for this, you should be safe. 如果为此使用ConcurrentDictionary ,则应该是安全的。

From the XmlDocument docs ; XmlDocument文档 ;

Thread Safety 线程安全

Any public static (Shared in Visual Basic) members of this type are thread safe. 此类型的任何公共static(在Visual Basic中为Shared)成员都是线程安全的。 Any instance members are not guaranteed to be thread safe. 不保证任何实例成员都是线程安全的。

So, no, use of your static instance is not guaranteed to be thread safe without locking. 因此,不,不能保证静态实例的使用在没有锁定的情况下是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM