title: Locking XML file in Web Application
body: <p>We have a website application which acts as a form designer.</p>
  
  <p>The form data is stored in XML file. Each form has it's own xml file.</p>
  
  <p>When i edit a form, i basically recreate the XML file.</p>
  
  <pre><code>public void Save(Guid form_Id, IEnumerable&lt;FormData&gt; formData)
  {
      XDocument doc = new XDocument();
      XElement formsDataElement = new XElement("FormsData");
      doc.Add(formsDataElement);
      foreach (FormData data in formData)
      {
          formsDataElement.Add(new XElement("FormData",
                                   new XAttribute("Id", data.Id)
                                   new XAttribute("Name", data.Name)
                                   // other attributes
                               ));
      }
  
      doc.Save(formXMLFilePath);
  }
  </code></pre>
  
  <p>This works good, but i want to make sure that two users won't update at the same time the XML file. I want to lock it somehow.</p>
  
  <p>How can i individually lock the save process for each file?</p>
  
  <p>I could lock the Save function like below, but this will lock all the users, even if they save a different XML file.</p>
  
  <pre><code>private static readonly object _lock = new object();
  public void Save(Guid form_Id, IEnumerable&lt;FormData&gt; formData)
  {
      lock(_lock)
      {
          XDocument doc = new XDocument();
          foreach (FormData data in formData)
          {
              // Code
          }
  
          doc.Save(formXMLFilePath);
      }
  }
  </code></pre>