gpt4 book ai didi

c# - .NET 锁定 IO 代码

转载 作者:行者123 更新时间:2023-11-30 22:14:53 25 4
gpt4 key购买 nike

我有几个客户端对象(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);
}

最佳答案

lock 不知道文件是什么。它对每个进程都存在的 CLR 对象进行操作。不同的进程会看到不同的对象。

你需要一些跨进程的互斥。以下是一些选项:

  1. 一个命名的Mutex
  2. 文件级锁定和重试策略(我怀疑 log4net 就是这样做的)
  3. 具有不同名称的多个文件(使用随机名称以免发生冲突)

选项 3 是最简单的。

关于c# - .NET 锁定 IO 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18274094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com