What is the best way to ensure thread-safe Linq-to-XML, for writing?
We recently got overloaded on our web cluster and I had to pull a quick overloaded.aspx out of my butt to capture emails that people can be contacted with later when the site becomes 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 wasn't able to lookup if Linq-to-XML was threadsafe; so, the theory went "let me just lock a static object, and that will prevent multiple writes." Was this the best approach? Was it even needed (is Linq-to-Xml thread safe?). Sad to say my two Pro LINQ and Linq in Action books don't touch on that subject.
This worked fine, and we captured an amount of emails in the 20m we were overloaded. Just wondering if there was a better way; or, if it was just overkill to lock it in the first place.