asp.net - Dealing with IOExceptions with XmlWriter.Create() and XmlDocument.Load() in separate threads -
i have inherited code involves scheduled task writes data (obtained external source) xml files, , website reads said xml files information presented visitor.
there no synchronization in place, , needless say, scheduled task fails write file because open reading.
the heart of writer code is:
xmlwriter writer = xmlwriter.create(filename); try { xmldata.writeto(writer); } { writer.close(); }
and heart of reader code is:
xmldocument thedocument = new xmldocument(); thedocument.load(filename);
(yep no exception handling @ either end)
i'm not sure how best approach trying synchronize these. far know neither xmlwriter.create() nor xmldocument.load() take parameters regarding file access modes. should manage underlying filestreams myself (with appropriate access modes) , use .create() , .load() overloads take stream parameters?
or should catch ioexceptions , sort of "catch, wait few seconds, retry" approach?
provided web site not need write xmldocument loaded, load via filestream
has fileshare.readwrite
set. should allow xmlwriter in other thread write file.
if not work, try reading xml filestream memorystream, , close file possible. still open file fileshare.readwrite, minimize amount of time reader needs access data in file.
by using fileshare.readwrite
(or fileshare.write
matter) sharing mode, run risk document updated while still reading it. result in invalid xml content, preventing xmldocument.load call parsing it. if wish avoid this, try synchronizing temporary "locking file". rather allowing file sharing, prevent either thread concurrently accessing, , when either of them processing file, write empty, temporary file disk indicates this. when processing (reading or writing) done, delete temporary file. prevents exception being thrown on either end, , allows synchronize access file.
there couple other options use well. let both ends swallow exception , wait short time before trying again, although isn't best design. if understand threading options of .net enough, use named system mutex
both processes (your writing process , web site process) know about. use mutex lock, , not have bother locking file.
Comments
Post a Comment