C# 需要使用异步数据库请求返回SqlDataReader
以下方法在SQL Server数据库中执行查询:C# 需要使用异步数据库请求返回SqlDataReader,c#,.net,sql-server,sql-server-2008,asynchronous,C#,.net,Sql Server,Sql Server 2008,Asynchronous,以下方法在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.ExecuteReaderAs
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
参数。最好的解决方法是什么?任务可以返回您需要的内容
private async Task<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 = await cmd.ExecuteReaderAsync();
if (!reader.HasRows)
{
return false;
}
while (reader.Read())
{
// do some stuff
if (some condition)
return true;
}
}
private异步任务已验证(SqlConnection-conn)
{
string query=“一些sql查询”;
SqlCommand cmd=新的SqlCommand(查询,连接);
//目的是将其更改为:SqlDataReader=await cmd.ExecuteReaderAsync();
SqlDataReader=await cmd.ExecuteReaderAsync();
如果(!reader.HasRows)
{
返回false;
}
while(reader.Read())
{
//做点什么
如果(某些条件)
返回true;
}
}
作为旁注,SqlConnection
类不是线程安全的。当异步请求挂起时,小心不要重用它。另外,请确保不再需要SqlConnection
实例时将其释放。否则,您可能会导致连接泄漏和饥饿。