I'm writing a Stringbuilder to file

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

This is equivilent (I think)

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

Obviously in a multi threaded environment these statements on their own would cause failures to write as they collided. I've put a lock on this code, but that isn't ideal, as it's too expensive and may exacerbate this bottleneck. Is there some other way of causing one threads file access to block another's. I've been told "blocking not locking", I thought lock did block, but they must be hinting at a cheaper way of preventing simultaneous use of the file system.

How do I block execution in a less time expensive manner?

有帮助吗?

解决方案

You can't have multiple threads write to the same file simultaneously, thus, there is no such "bottleneck" . A lock makes perfect sense for this scenario. If you are concerned about this being expensive, just add the writes to a queue, and let a single thread manage writing them to file.

Pseudo code

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);
}

其他提示

You can lock the stream using the lock method.

http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top