LINQ to XML updates - how does it handle multiple concurrent readers / writers?

I have an old system that uses XML to store data. I am about to use data for another mini project and would like to use LINQ to XML to query / update data; but there are 2 scenarios that I'm not sure if I need to handle it myself or not:

1- If I have something similar to the following code and 2 people get to Save () at the same time? LINQ to XML waits until the file appears again before saving it, or will it just throw it away? I don't want to set locks if I don't need to :)

// I assume the next line doesn't lock the file
XElement doc = XElement.Load("Books.xml");
XElement newBook = new XElement("Book",
new XAttribute("publisher", "My Publisher"),
new XElement("author", "Me")));
doc.Add(newBook);

// What happens if two people try this at the same time?
doc.Save("Books.xml");

      

2- If I load () the document, add an entry under the specific node and then click "Save" (); what happens if another user has already added a value under that node (since I clicked on Load ()), or worse, deleted the node?

Obviously I can solve these problems, but I couldn't find any documentation that could tell me if I have it or not, and the first one would at least be a bit of a pig to test it reliably.

0


source to share


1 answer


This is not a LINQ to XML issue, but a core concurrency issue.



  • Assuming that two people pressed the Save button at the same time, and the backup location is a file, then depending on how you opened the file to save, you might get an error message. If you leave it in the XDocument class (just passing in the filename), then most likely it opens it exclusively, and someone else trying to do the same (on the same code stroke) will get an exception. You basically have to sync access to whatever share you read / write from.

  • If another user has already added the value, provided that you have no problem getting the resource to write, your changes will overwrite the resource. This is a common problem with databases known as optimistic concurrency and you need some value to indicate if a change occurred between the time the data was loaded and the save (most databases will generate timestamp values โ€‹โ€‹for you).

+1


source







All Articles