Using Linq-to-XML for Insert Using Streaming

What is the best way to provide thread-safe Linq-to-XML for writing?

We recently rebooted into our web cluster, and I had to pull a fast overloaded .aspx from my stock to grab emails that could be contacted later when the site became more responsive. In my short 5 minute haste, I wrote this:

private static object LockHandle = new object();

protected override void OnLoad(EventArgs e)
{
  SubmitButton.ServerClick += new EventHandler(SubmitButton_ServerClick);
  base.OnLoad(e);
}

void SubmitButton_ServerClick(object sender, EventArgs e)
{
  string email = Email.Value.Trim();
  if (email.Length > 0)
  {
    Regex regex = new Regex(@"^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$");
    if (regex.IsMatch(email))
    {
      lock (LockHandle)
      {
        try
        {
          string fileName = Server.MapPath("emails.xml");
          XDocument xdoc = XDocument.Load(fileName);
          xdoc.Element("emails").Add(new XElement("email", email));
          xdoc.Save(fileName);
        }
        catch {}
      }

      ResponseText.Text = "Thanks! We'll get back to you.";


    }
  }
}

I could not find if Linq-to-XML was thread safe; therefore, the theory "allowed me to simply lock the static object, and this would prevent multiple entries." Is this a better approach? Was it even necessary (Linq-to-Xml thread safe?). Unfortunately, my two books Pro LINQ and Linq in Action do not address this issue.

, 20-, . , ; , , .

+3
3

, , .

+2

, MSDN, , . .

, MS .

, , load/edit/save. , ( , FileStram /, ( StreamReader StreamWriter) ).

- ( ), , . , , (, , , ).

+2

, LINQ , .Net SDK-:

  • .
+1

Source: https://habr.com/ru/post/1703536/


All Articles