Thread safety when using XML API in VB.NET

I have a question about thread safety using XML in VB.NET.

I have an application that manages an XmlDocument object when a user creates new elements / makes changes to existing elements. I already know that I need to synchronize calls with XmlDocument.CreateElement(...) . My question is, can I then proceed to create the returned element without synchronization, and then just synchronize again when this element is added to the XmlDocument ?

This is what I think I can do, I just need to make sure it is thread safe, as I think it is:

 ' "doc" object already exists as an XmlDocument SyncLock doc Dim newsub As XmlElement = doc.CreateElement("submission") End SyncLock ' use "newsub" here without synchronization SyncLock doc doc.Item("submissions").AppendChild(newsub) End SyncLock 

When adding newsub children, I also only sync when I create each item.

As a continuation of this question, would I be better off just syncing the entire building of the newsub? The reason I think doing it as above is better for performance, but I am by no means an expert on whether I really have a significant impact on performance or just complicate things.

+4
source share
1 answer

In general, when using any class derived from XmlNode , you will need synchronization, as the documentation explicitly states:

All public static (Shared in Visual Basic) members of this type are thread safe. Any instance members do not guarantee thread safety.

This means that you will need synchronization when adding children, as you showed.

As a continuation of this question, would I be better off just syncing the entire building of the newsub? The reason I think doing it as above is better for performance, but I am by no means an expert on whether I really have a significant impact on performance or just complicate things.

It depends - if you are going to do something that could lead to its use from several threads, you may need to synchronize it.

In the above code, it should be safe to work with newsub outside of synchronization, since it is not part of the actual document tree until you add it as a child. This will reduce the time during which the doc locked, which can reduce the conflict if the doc used from multiple threads.

+4
source

Source: https://habr.com/ru/post/1482001/


All Articles