0

I have quite a bit of users accessing the same XML file. Is the code below the best way to access the file? If not, what is preferred? I don't want the user to get a "file in use error" or something to that nature.

private readonly XDocument _xmlDocument;

public SubCategoriesParser(string filePath)
{
    if (filePath != null)
        _xmlDocument = XDocument.Load(filePath);
}
2
  • 2
    Why does it make sense to have multiple users update a text file at the same time? Commented Dec 20, 2011 at 23:06
  • It's a web application. It makes no sense to have multiple users update a text file at the same time (unless it's one file per user). Commented Dec 20, 2011 at 23:32

2 Answers 2

3

You can use the System.Threading.ReaderWriterLock class to solve your scenario. This class supports one writer and multiple readers. There's a nice example at the link provided.

Sign up to request clarification or add additional context in comments.

1 Comment

@BojanSkrchevski Why that over ReaderWriterLockSlim? I'd say you should pretty much always use the slim unless you've a clear reason not to.
1

You could synchronise access to the file with a lock, or (should you have the sort of reader-to-writer ratio that makes it reasonable) a ReaderWriterLockSlim.

I would rather avoid the whole question though. Databases are built to handle this sort of multiple concurrent use, so that's an alternative. If you could split your logic out over multiple files, that's an other possibilty.

Otherwise, at least you only have to lock on Save and Load to avoid corruption to the file. You would have to be very careful with making the locks finer in this way though, since saves will over-write each other in ways that lose data that wouldn't have been lost if you were syncronising on the entire operation.

2 Comments

lock (this) { _xmlDocument = XDocument.Load(filePath); } Does this look ok?
Never ever ever lock this. Apart from that though, and do the same on save, and then double and triple-check your logic to be sure that at thread writing over a change that happened after it had loaded its XDocument is okay - if it isn't you'll have to lock on the whole thing (which is likely to be nasty if there'll be many cases of real contention rather than this being a just-in-case locking).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.