Skip to main content
 首页 » 编程设计

c#之写入文件系统。如何有效锁定

2024年02月13日35lori

我正在写一个 Stringbuilder 到文件

   using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read)) 
   using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode)) 
   { 
        writer.Write(text.ToString()); 
   } 

这是等价的(我认为)

   File.AppendAllText(Filepath, text.ToString()); 

显然,在多线程环境中,这些语句本身会在它们发生冲突时导致写入失败。 我在这段代码上加了一个锁,但这并不理想,因为它太昂贵并且可能会加剧这个瓶颈。是否有其他方法导致一个线程文件访问阻塞另一个。有人告诉我“阻塞而不是锁定”,我认为 lock 确实阻塞了,但他们一定是在暗示一种更便宜的方式来防止同时使用文件系统。

如何以更省时的方式阻止执行?

请您参考如下方法:

你不能让多个线程同时写入同一个文件,因此,不存在这样的“瓶颈”。 lock 非常适合这种情况。如果您担心这会很昂贵,只需将写入添加到队列中,然后让单个线程管理将它们写入文件。

伪代码

public static readonly Object logsLock = new Object(); 
 
// any thread 
lock(logsLock)  
{ 
    logs.Add(stringBuilderText); 
} 
 
// dedicated thread to writing 
lock(logsLock) 
{ 
    // ideally, this should be a "get in, get out" situation,  
    // where you only need to make a copy of the logs, then exit the lock,  
    // then write them, then lock the logsLock again, and remove only the logs  
    // you successfully wrote to to file, then exit the lock again. 
    logs.ForEach(writeLogToFile); 
}