title: .NET locking IO code
body: <p>I have several Client objects (TCPClient wrappers) operating on separate threads. If any of these objects encounters a problem an error message is saved to an XML error log. Obviously file access is restricted to one process at a time so I need a way of preventing other threads from reading/writing while another is using it.</p>
  
  <p>I'm currently using the <code>lock</code> method however an exception is still thrown that another process is using the file. I was under the impression <code>lock</code> will manage waiting and retrying.</p>
  
  <pre><code>// Lock the XML IO for safety due to multi-threading
  lock (this.xmlDoc) // Changed from this to the xmlDoc
  {
      // Attempt to 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"));
      }
      // Get the doc root
      XmlElement root = this.xmlDoc.DocumentElement;
      // Create message entry
      XmlElement msg = this.xmlDoc.CreateElement("message");
      // Add &lt;time&gt;&lt;/time&gt; to msg
      msg.AppendChild(this.xmlDoc.CreateElement("time")).InnerText = dt.ToString();
      // Add &lt;error&gt;&lt;/error&gt; to msg
      msg.AppendChild(this.xmlDoc.CreateElement("error")).InnerText = message;
      // Add msg to root
      root.AppendChild(msg);
      // Save. Done.
      this.xmlDoc.Save(this.logPath);
  }
  </code></pre>