Попробуйте ввести lock
, посмотрите, решит ли это проблему:
// Declare this somewhere in your project, can be in same class as WriteToXML
static object XmlLocker;
Затем оберните lock
вокруг логики:
public void WriteToXML(object param)
{
Expense exp = (Expense)param;
lock (XmlLocker) // <-- this limits one thread at a time
{
if (File.Exists(filepath))
{
XDocument xDocument = XDocument.Load(filepath);
XElement root = xDocument.Element("Expenses");
IEnumerable<XElement> rows = root.Descendants("Expense");
XElement firstRow = rows.First();
firstRow.AddBeforeSelf(new XElement("Expense",
new XElement("Id", exp.Id.ToString()),
new XElement("Amount", exp.Amount.ToString()),
new XElement("Contact", exp.Contact),
new XElement("Description", exp.Description),
new XElement("Datetime", exp.Datetime)));
xDocument.Save(filepath);
}
}
}