[英]Unable to write to XML file using threads and XDocument
string filepath = Environment.CurrentDirectory + @"Expense.xml";
public void WriteToXML(object param)
{
Expense exp = (Expense)param;
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);
}
}
Expense exp = new Expense();
exp.Id = new Random().Next(1, 10000);
exp.Amount = float.Parse(text1[count].Text);
exp.Contact = combo1[count].SelectedItem.ToString();
exp.Description = rtext1[count].Text.ToString();
exp.Datetime = DateTime.Now.ToString("MM-dd-yyyy");
workerThread = new Thread(newParameterizedThreadStart(WriteToXML));
workerThread.Start(exp); // throws System.IO.IOException
我無法使用輔助程序寫入XML文件-我收到此錯誤:
System.IO.IOException:'該進程無法訪問文件'C:\\ work \\ FinanceManagement \\ FinanceManagement \\ bin \\ DebugExpense.xml',因為該文件正在被另一個進程使用。
但是如果我像WriteToXML(exp);
一樣使用它WriteToXML(exp);
有用。 我認為XDocument.Load(filepath)
不是線程安全的。 我該如何解決這個問題?
嘗試引入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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.