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);
        }
    }
     
  • 相关阅读:
    Django models中的null和blank的区别
    微服务
    幂等性
    restful规范
    related_name
    数据库 引擎,数据类型,约束
    数据库 基本操作
    python 常见算法
    python if,循环的练习
    python数据类型、if判断语句
  • 原文地址:https://www.cnblogs.com/Javi/p/13277883.html
Copyright © 2011-2022 走看看