The following method executes a query in a SQL Server database:
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;
*/
}
}
The method call to execute the query needs to be changed to an asynchronous version. However, the method would need to be changed to an async. Such methods cannot return anything other than void or Task. Writing another method just for the query execution has been considered, but aysnc methods cannot take ref parameters. What is the best way out of this?
SqlConnectionclass is not thread-safe. Be careful not to reuse it while an asynchronous request is pending. Also make sure that theSqlConnectioninstance is disposed when it's no longer needed. Otherwise you may end up with a connection leakage, and a starved connection pool.