我有几个在不同线程上运行的客户端对象(TCPClient 包装器)。如果这些对象中的任何一个遇到问题,则会将错误消息保存到 XML 错误日志中。显然,文件访问一次仅限于一个进程,所以我需要一种方法来防止其他线程在另一个线程使用它时读取/写入。
我目前正在使用该lock
方法,但是仍然会引发另一个进程正在使用该文件的异常。我的印象是lock
会管理等待和重试。
// Lock the XML IO for safety due to multi-threading
lock (this.xmlDoc) // Changed from this to the xmlDoc
{
// Attempt to load existing xml
try
{
this.xmlDoc.Load(this.logPath);
}
catch (FileNotFoundException e)
{
// xml file doesn't exist, create
this.xmlDoc.AppendChild(this.xmlDoc.CreateElement("root"));
}
// Get the doc root
XmlElement root = this.xmlDoc.DocumentElement;
// Create message entry
XmlElement msg = this.xmlDoc.CreateElement("message");
// Add <time></time> to msg
msg.AppendChild(this.xmlDoc.CreateElement("time")).InnerText = dt.ToString();
// Add <error></error> to msg
msg.AppendChild(this.xmlDoc.CreateElement("error")).InnerText = message;
// Add msg to root
root.AppendChild(msg);
// Save. Done.
this.xmlDoc.Save(this.logPath);
}