3

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?

1
  • As a side note, the SqlConnection class is not thread-safe. Be careful not to reuse it while an asynchronous request is pending. Also make sure that the SqlConnection instance is disposed when it's no longer needed. Otherwise you may end up with a connection leakage, and a starved connection pool. Commented Apr 14, 2020 at 15:44

1 Answer 1

2

Task<T> can return what you need.

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.