【发布时间】:2020-07-27 02:21:22
【问题描述】:
以下方法在 SQL Server 数据库中执行查询:
private bool authenticated(SqlConnection conn)
{
string query = "some sql query";
SqlCommand cmd = new SqlCommand(query, conn);
// the intent is to change this to: SqlDataReader reader = await cmd.ExecuteReaderAsync();
SqlDataReader reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
return false;
}
while (reader.Read())
{
// do some stuff
/*
if (some condition)
return true;
*/
}
}
执行查询的方法调用需要改为异步版本。但是,该方法需要更改为async。此类方法不能返回除void 或Task 以外的任何内容。已经考虑为查询执行编写另一种方法,但aysnc 方法不能采用ref 参数。最好的方法是什么?
【问题讨论】:
-
附带说明,
SqlConnection类不是线程安全的。小心不要在异步请求挂起时重用它。还要确保在不再需要SqlConnection实例时将其释放。否则你最终可能会出现连接泄漏和饥饿的connection pool。
标签: c# .net sql-server sql-server-2008 asynchronous