如何将sqlDataReader转换为Task async

时间:2017-06-03 07:13:13

标签: c# async-await sqlconnection sqlcommand

我有以下代码 - 任何人都可以告诉我是否可以将其设为异步任务

public  MDTO GetIe(MDTO dtoItem)
    {

        string[] Tables = new string[] { "C", "CValue", "SP", "Ar", "P", "CR", "QC", "SR" };
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["tESTp"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("GetItem", connection))
            {
                DataSet Result = new DataSet();
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@ProjectId", SqlDbType.VarChar);
                command.Parameters["@ProjectId"].Value = dtoItem.ProjectId;


                connection.Open();
                Result.EnforceConstraints = false;
                Result.Load(command.ExecuteReader(CommandBehavior.CloseConnection), LoadOption.OverwriteChanges, Tables);
                dtoItem.SR = Result;
            }
        }
        return dtoItem;
    }

1 个答案:

答案 0 :(得分:2)

将command.ExecuteReader更改为异步版本:

public async Task<MDTO> GetIeAsync(MDTO dtoItem)
{
    ...
    connection.Open();
    Result.EnforceConstraints = false;

    SqlDataReader dataReader = await command.ExecuteReaderAsync(CommandBehavior.CloseConnection);
    Result.Load(dataReader, LoadOption.OverwriteChanges, Tables);
    dtoItem.SR = Result;
    ...
}