简体   繁体   中英

C# best way to use sql connection in async task

net core web api project. I commonly use logs everywere in my apps to have some additional tracking capabilities for overall system health. Currently, my "logging" happens synchronously, for instance

void MyMethod()
{
   Log.Write("initiating");
   //Do Something
   Log.Write("finished");
}

Now, Log.Write() will consume time in the main thread as it's, after all, a sql insert. How can I make Log.Write be, both asynchronous (Task.Run style for which i need no return value, so no awaiting) AND resolve its own sql connection? If Log.Write() uses the same connection my controller/method has, it will be disposed after the main execution and I risk not having an open connection when the async task runs. So Write() must resolve its own connection and it is a method that might be called hundred if not thousands of times a minute.

Thanks!

Microsoft themselves states that async logging methods should not be necessary since you should not be logging to a slow store:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging#no-asynchronous-logger-methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM