C# Writing To Text File Safely With Heaps of Threads

佐手、 提交于 2019-12-03 21:22:58

No, the StringBuilder is not thread safe, so multiple threads using it at the same time may corrupt it.

Synchronise the access to the StringBuilder using the lock keyword. Make it private, and supply public methods to work with it safely:

private static StringBuilder _sb = new StringBuilder();
private static object _sbSync = new Object();

public static void AppendLine(string line) {
  lock (_sbSync) {
    _sb.appendLine(line);
  }
}

public static string GetLines() {
  lock (_sbSync) {
    string result = _sb.ToString();
    _sb = new StringBuilder();
    return result;
  }
}

We can use ReaderWriterLockSlim http://www.johandorper.com/log/thread-safe-file-writing-csharp

private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();

public void WriteToFile(string text, string path) 
{
    _readWriteLock.EnterWriteLock();
    using (StreamWriter sw = new StreamWriter(path, true))
    {
        sw.WriteLine(text);
        sw.Close();
    }
    _readWriteLock.ExitWriteLock();
}

I would suggest not having each of those threads write to the file, but write to a shared memory resource instead (a Singleton that you can access from every thread), and then have that Singleton write to the file ONLY when necessary -- say, at the end of your program. That way only one thread accesses I/O and you'll be much safer.

Obviously the Singleton you write must be thread-safe too, so you must control writes to it with a lock.

Good luck!

If you are using .Net framework v4 or above, take a look at the data structures in the System.Collections.Concurrent Namespace; particularly, the BlockingCollection<T> Class. The BlockingCollection has some useful methods like TakeFromAny typically designed to serve a producer - consumer scenario such as the one you describe.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!