I have an application that uses an XML file to store certain data that does not need to be in the DB. This file, while rarely, might be written to between pages at the same time. This creates an issue, most probably causing one of the pages to crash. I was wondering if there is a way to have a page render wait until the other is done writing to the file.
I am not sure if I can assume that every page render runs in its own thread; if it does, then can I halt that thread like a lock() command to wait for the resource to be available. If so, how can I implement a lock() on a file (since its not a memory segment)?
If its not threaded or I cannot use lock(), what other ways are there to make sure that the file is written to, but if someone else is using that file, it can wait for the file to be available?
There are a lot of methods of managing write order and rights but for this it is simple; if you came second, you will write in after the other person is done. I am not so concerned with write collisions at this point, but concurrent writing is something that needs to be addressed.
Any help is greatly appreciated!
If it’s from a single machine, you could use a
Semaphorehttp://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx:That’s kind of like a system-wide lock. Not great though, would suggest a DB. Plus, other things might cause file access to fail. You could implement something which creates a
FileStreamwith the appropriate locking mode, which will fail if you try to open for writing by two sources, but it won’t do alock-like scenario (which uses theMonitorclass internally)Btw: “does not need to be stored in the DB”. The fact you’re asking this question suggests it really should be. If that’s a pain to implement, you might want to rethink your data access strategy. Stuff like Entity Framework w/ Code First makes it very easy to “chuck” stuff in the DB.