Simple MultiThread Safe Log Class

后端 未结 5 553
轻奢々
轻奢々 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:14

    you need to declare the sync object at the class level:

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

    Might be better to declare your logging class as static, and the locking object as @Adam Robinson suggested.

提交回复
热议问题