Simple MultiThread Safe Log Class

后端 未结 5 536
轻奢々
轻奢々 2021-01-02 01:26

What is the best approach to creating a simple multithread safe logging class? Is something like this sufficient? How would I purge the log when it\'s initially created?

5条回答
  •  温柔的废话
    2021-01-02 02:05

    No, you're creating a new lock object every time the method is called. If you want to ensure that only one thread at a time can execute the code in that function, then move locker out of the function, either to an instance or a static member. If this class is instantiated every time an entry is to be written, then locker should probably be static.

    public class Logging
    {
        public Logging()
        {
        }
    
        private static readonly object locker = new object();
    
        public void WriteToLog(string message)
        {
            lock(locker)
            {
                StreamWriter SW;
                SW=File.AppendText("Data\\Log.txt");
                SW.WriteLine(message);
                SW.Close();
            }
        }
    }
    

提交回复
热议问题