zoukankan      html  css  js  c++  java
  • 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);
        }
    }
     
  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/Javi/p/13277883.html
Copyright © 2011-2022 走看看