Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

c# - Creating ConsoleLogger directly astonishingly doesn't work

Can someone explain to me why this doesn't just work? This feels astonishing to me. If this is not a viable usage, I would say that this is a design smell. I should either be not permitted to do this by the API's design, or I would expect a useful error.

    public static void Main(string[] args)
    {
        var l = new ConsoleLogger("test", (s, ll) => true, true);
        l.WriteMessage(LogLevel.Critical, "test", 0, "hello world", null);
    }

This implementation outputs literally nothing. Why? I don't feel like I should have to use the DependencyInjection and service location mechanisms.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess it's because of the fire and forget (Task.Factory.StartNew) implementation. See here. (In other words, the code doesn't wait for the message to be printed.)

If you do this:

var l = new ConsoleLogger("test", (s, ll) => true, true);
for (int i = 0; i < 10000; i++)
{
   l.WriteMessage(LogLevel.Critical, "test", 0, "hello world", null);
}

it works fine and the messages are being printed.

If you need to do the console logging synchronously, I suggest you implement your own console logger where you await the logging operation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...