Creating ConsoleLogger directly astonishingly doesn't work

本秂侑毒 提交于 2019-12-13 22:03:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/47424051/creating-consolelogger-directly-astonishingly-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!