“Any public static members of XmlDocument are thread safe. Any instance members are not guaranteed to be thread safe” : yes, but

廉价感情. 提交于 2021-02-10 14:19:42

问题


I see in the XmlDocument class documentation on MSDN that

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Same thing for the XmlNodeList class.

I am using those classes in the following context. Inside a Parallel.Foreach I do :

X MyX = new X();
string XMLstring = MyX.GetXML(ID, true);
XmlDocument doc = new XmlDocument();
doc.LoadXml(XMLstring);
XmlNodeList nodeList = doc.SelectNodes("blah/secondblah");

where X is defined in a library the IT's are providing to me and where ID is an int (roughly on which I loop).

This has been tested thoroughly in a non parallel context, the strings produced by GetXML are indeed correct, the corresponding XmlDocument as well, and "parsing" it via XmlNodeList provides the expected results.

Now, it this parallel context and assuming that X and GetXML are indeed thread-safe, does the fact that I new an XmlDocument in every loop ensure thread-safety or not ? I mean, how can I know that the string member (first of all is there such a string ? as I don't see any string property in the document) of XmlDocument receiving the LoadXml is static or not ?

I suppose I don't really understand the bit of MSDN documentation I am quoting above ...


回答1:


The documentation means that any methods that are static (which would look like XmlDocument.MethodCall are thread-safe. That isn't relevant to you - you aren't calling any of those. Other methods (e.g. against doc) are not static - so they are not guaranteed to be thread-safe.

Your code will be 100% fine, as long as doc (and nodeList and other 'non thread-safe' variables) are used solely within the context of a single thread.

So if you populated doc before the Parallel.ForEach and then used doc inside the Parallel.ForEach - that won't work.

But if you populate and used doc inside the Parallel.ForEach you will be fine (since each thread will get its 'own doc'- thus thread-safety won't be an issue).

To be 100% sure, you'd need to post the entire method (including the Parallel.ForEach call) for us to have a look at.




回答2:


Yes it is thread safe. You are not sharing anything between threads. I have used similar XmlDocument code in large multi-threaded applications without problems. In theory there could be private static data in XmlDocument that we don't know about which is not thread safe, but my experience is that this is not the case. I think the MSDN documentation is implying that Microsoft have made sure that any static stuff which may be shared across threads, is in fact thread safe.



来源:https://stackoverflow.com/questions/44367866/any-public-static-members-of-xmldocument-are-thread-safe-any-instance-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!