简体   繁体   English

C# 在异步任务中使用 sql 连接的最佳方式

[英]C# best way to use sql connection in async task

net core web api project. net core web api 项目。 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.现在,Log.Write() 将在主线程中消耗时间,因为它毕竟是一个 sql 插入。 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?我怎样才能让 Log.Write 既是异步的(Task.Run 样式,我不需要返回值,所以不需要等待)并解决它自己的 sql 连接? 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.如果 Log.Write() 使用与我的控制器/方法相同的连接,它将在主执行后被处理,并且当异步任务运行时我可能没有打开连接。 So Write() must resolve its own connection and it is a method that might be called hundred if not thousands of times a minute.所以 Write() 必须解析它自己的连接,并且它是一种每分钟可能被调用数百次甚至数千次的方法。

Thanks!谢谢!

Microsoft themselves states that async logging methods should not be necessary since you should not be logging to a slow store: Microsoft 自己声明异步日志记录方法不是必需的,因为您不应该将日志记录到慢速存储:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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