views:

358

answers:

4

in my application (c# 3.5) there are various processes accessing a single xml file (read and write) very frequently. the code accessing the file is placed in an assembly referenced by quite a couple of other applications. for example a windows service might instanciate the MyFileReaderWriter class (locatied in the previously mentioned assembly) and use the read/write methods of this class.

i'm looking for the best/fastest way to read and create/append the file with the least amount of locking. caching the files data and flushing new content periodically is not an option, since the data is critical.

I forgot to mention that I currently use the XDocument (LInq2Xml infrastructure) for reading/writing the content to the file.

+3  A: 

To start with, make sure that all access to the XML Document is done through a single instance.

Then put a lock mechanism (that wait for unlock) at the beginning of the function that access it and unlock it at the end.

Hapkido
+1  A: 

What do you mean the data is critical? Is the XML file not exclusively used by your application?

As simple (and maybe good enough) way to lock IO access to the file would be to create a static factory class that provides a "read write token" object that each I/O operation would have to have a lock on.

public static object GetReadWriteToken(String fileName)
{
    //use a hashtable to retreive an object, with filename as key
    return token;
}

and simply do this while reading and writing:

lock(GetReadWriteToken(@"C:\important.xml"))
{
    //io code
}
biozinc
A: 

Please have a look at the following link

http://stackoverflow.com/questions/119548/problem-in-writing-to-single-file-in-web-service-in-net

pradeeptp
+4  A: 

If by writing you're only appending to the document, then try this

http://msdn.microsoft.com/en-us/library/aa302289.aspx

Basically your xml document is a shell with a start and end tag. Between the tags is an include reference, that references another file, this other file is the body of the xml document. For write operations this is many times faster, because you don't have to load the xml file each time you write to it, and you don't write the entire file each time.

Using an XmlWriter class you can very easily append nodes to the end of the body file.

When others want to read the xml, they simply open the document, their xml parser "knows" to load and parse both files.

Hope this helps.

Binary Worrier