Do the “StreamWriter.WriteLine()” function need to “lock()”?

question:

i develop a class to write logs. it writes with "StreamWriter.WriteLine()" function.

logStream.WriteLine(msgWrite);
logStream.Flush();

some different threads use this class to write logs, in one text file(The log file is common for all threads) do it need to lock() function?

should i change my code?

lock(syncObj)
{
    logStream.WriteLine(msgWrite);
    logStream.Flush();
}


Answer:

You should wrap your writer in TextWriter.Synchronized which, as that document suggests, ensures that all resulting write operations are performed in a thread-safe manner.

Aside from that, yes, you could just use a lock to do it, but when there's built-in functionality like this I tend to prefer it.

A quick-and-dirty implementation could look something like this:

public static class Logs
{
    static Logs()
    {
        _Writer = TextWriter.Synchronized(new StreamWriter(path));
    }

    private static TextWriter _Writer;

    static void LogLine(string line)
    {
        _Writer.WriteLine(line);
    }
}
 
posted @ 2020-07-10 10:15  Javi  阅读(177)  评论(0编辑  收藏  举报