Навигация

Итоги года

Другие ссылки


Реклама

Счётчики


XmlDocument.Load locks for writing

25.05.2007 Пятница 18:01

Yesterday I saw the following error message in the Event Log:

The process cannot access the file 'C:\Bla-bla.Config.xml' because it is being used by another process.

Exception type: IOException
Source: mscorlib
Target Site: Void WinIOError(Int32, System.String)


The error was happening in a function that was attempting to write to the file. I remembered that previously I had a similar issue that was caused by incorrect locking used to prevent multiple threads from writing simultaneously to the file (link). I tweaked code to make locking mechanism work as expected but... surprisingly, I still got the same message.

I spent some time digging for real cause of the problem. Finally, I found out that XmlDocument.Load(System.String) function, that was used in other places in code to read the same file, for some reason locks the file when openning it. You can read but you can't write.

I solved the issue by replacing

XmlDocument doc = new XmlDocument();
doc.Load("C:\Bla-bla.Config.xml");
with

XmlDocument doc = new XmlDocument();
using (FileStream stream = new FileStream
("C:\Bla-bla.Config.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
doc.Load(stream);
stream.Close();
}
Question remains open as to what will happen when a thread attempts to read the file when it's being written to by another thread. May be locking should be implemented on read attempts too.