c# - .NET locking IO code -


i have several client objects (tcpclient wrappers) operating on separate threads. if of these objects encounters problem error message saved xml error log. file access restricted 1 process @ time need way of preventing other threads reading/writing while using it.

i'm using lock method exception still thrown process using file. under impression lock manage waiting , retrying.

// lock xml io safety due multi-threading lock (this.xmldoc) // changed xmldoc {     // attempt load existing xml     try     {         this.xmldoc.load(this.logpath);     }     catch (filenotfoundexception e)     {         // xml file doesn't exist, create         this.xmldoc.appendchild(this.xmldoc.createelement("root"));     }     // doc root     xmlelement root = this.xmldoc.documentelement;     // create message entry     xmlelement msg = this.xmldoc.createelement("message");     // add <time></time> msg     msg.appendchild(this.xmldoc.createelement("time")).innertext = dt.tostring();     // add <error></error> msg     msg.appendchild(this.xmldoc.createelement("error")).innertext = message;     // add msg root     root.appendchild(msg);     // save. done.     this.xmldoc.save(this.logpath); } 

lock not know file is. operates on clr objects, exist per process. different process see different object.

you need cross-process mutual exclusion. here options:

  1. a named mutex
  2. file-level locking , retry strategy (i suspect log4net way)
  3. multiple files different names (use random names don't collisions)

option 3 easiest.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -