developing logger object for a multi threaded system

时间:2019-05-31 11:49:51

标签: c# logging synchronization

I had this interview question: Given a multi threaded system, how should a logger object be designed?

I said it should be static, use singleton design pattern and using a locking mechanism:

public class Logger{

    private Logger(){
        Console.WriteLine("Logger created");
    }

    static Logger instance;
    static Object key = new Object();

    public static Logger getInstance(){
        lock (key){
            if  (instance == null){
                instance = new Logger();
            }
        }
        return instance;
    }   
}


Now I am wondering about the key object initialization - It should be thread safe and it should be initialized once (the same features I need for my logger) - so I developed next solution :

public class Logger{

    private Logger(){
        Console.WriteLine("Logger created");
    }

    static Logger instance = new Logger();

    public static Logger getInstance(){
            return instance;
    }   
}

Are those solutions basically the same?

0 个答案:

没有答案