【问题标题】:Need to return SqlDataReader with asynchronous database request需要用异步数据库请求返回 SqlDataReader
【发布时间】: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。此类方法不能返回除voidTask 以外的任何内容。已经考虑为查询执行编写另一种方法,但aysnc 方法不能采用ref 参数。最好的方法是什么?

【问题讨论】:

  • 附带说明,SqlConnection 类不是线程安全的。小心不要在异步请求挂起时重用它。还要确保在不再需要 SqlConnection 实例时将其释放。否则你最终可能会出现连接泄漏和饥饿的connection pool

标签: c# .net sql-server sql-server-2008 asynchronous


【解决方案1】:

Task<T>可以返回你所需要的。

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;
    }
}

【讨论】:

    猜你喜欢
    • 2013-04-05
    • 2015-04-07
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多