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 string
s 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 ...
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.