[英]C#, Dapper, SQL Server and Connection Pooling
I've written some code to write some data to SQL Server, using Dapper. 我已经编写了一些代码,以使用Dapper将一些数据写入SQL Server。 I don't need to wait for this write to complete before continuing other work, so want to use Task.Run() to make this asynchronous. 在继续其他工作之前,我不需要等待此写操作完成,因此想使用Task.Run()使其异步。
I have (using) statements for calling this in the rest of my system: 我在系统的其余部分中有(使用)语句来调用此语句:
using (IDataAccess ida = new DAL())
{
ida.WriteMessageToDB(id, routingKey, msgBody);
}
My DAL will automatically check the dbConnection.State when the using statement is ran, and attempt a simple fix if it's closed. 运行using语句时,我的DAL将自动检查dbConnection.State,并在关闭后尝试进行简单修复。 This works just fine for any non-async/TPL select calls. 这对于任何非异步/ TPL选择调用都很好。
However, when I throw a load of writes at the same time, the Task.Run() code was falling over as the connection was closed for some of them - essentially I think the parallel nature of the code meant the state was being closed by other tasks. 但是,当我同时抛出大量写入操作时,由于其中一些连接已关闭,因此Task.Run()代码崩溃了–本质上,我认为代码的并行性质意味着状态被关闭。其他任务。
I 'fixed' this by doing a check to open the Connection.State within the Task.Run() code, and this appears to have 'solved' the problem. 我通过检查以在Task.Run()代码中打开Connection.State来“解决”此问题,这似乎已“解决”了问题。 Like so: 像这样:
Task.Run(() =>
{
if (dbConnection.State == ConnectionState.Closed)
{
dbConnection.Open();
}
if (dbConnection.State == ConnectionState.Open)
{
*Dapper SQL String and Execute Commands*
}
});
When I run SELECT * FROM sys.dm_exec_connections
from SSMS after this, I see a lot more connections. 之后,当我从SSMS运行SELECT * FROM sys.dm_exec_connections
,我看到了更多的连接。 To be expected? 可以期待?
Now as I understand it: 现在,据我了解:
Is there anything wrong with this solution? 这个解决方案有什么问题吗? Or a better way of doing it? 还是更好的方法呢? I'd like to use connection pooling for obvious reasons, and as painlessly as possible. 我想使用连接池的原因很明显,并且要尽可能地轻松。
Thanks in advance. 提前致谢。
Thanks Juharr - I've upvoted your reply. 感谢Juharr-我已对您的答复表示支持。
For reference to others, I changed write function to await and Dapper async: 作为参考,我将write函数更改为await和Dapper异步:
private async Task WriteMessageToDB(Guid id, string tableName, string jsonString)
{
string sql = *Redacted*
await dbConnection.ExecuteScalarAsync<int>(sql, new { ID = id, Body = jsonString });
}
And then created a new task in the caller that monitors the outcome. 然后在调用方中创建一个监视结果的新任务。
This is working consistently under load, and not seeing excessive new connections being created either. 这在负载下始终如一地工作,也没有看到过多的新连接被创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.