我正在写一个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
确实阻塞了,但他们一定是在暗示一种更便宜的方法来防止同时使用文件系统。
如何以更节省时间的方式阻止执行?
不能让多个线程同时写同一个文件,因此,不存在这样的"瓶颈"。对于这种情况,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);
}
可以使用lock方法锁定流。
http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx