async await疑问

2019-07-24 07:45发布

问题:

public async Task<PagerModel<ResultModel>> GetList()
{
PagerModel<ResultModel> result = new PagerModel<ResultModel>();

        sql = "";
        sqlCount = "";

        using (IDbConnection connection = ConnectionManager.OpenConnection())
        {                
            var temp = await connection.QueryAsync<ResultModel>(sql);
            result.TotalCount = await connection.ExecuteScalarAsync<int>(sqlCount);
            result.PagerList = temp.Distinct().ToList();
            result.TotalPageCount = (int)Math.Ceiling((double)result.TotalCount / pageSize);

            connection.Close();
            connection.Dispose();
        }
        return result;
    }

请问上面代码为什么不异步执行呢,两个异步方法每个在300 -400ms,现在接口监测耗时共900ms左右。该怎么写呢,万分感谢!

回答1:

var tempTask = connection1.QueryAsync<ResultModel>(sql);
var totalTask = connection2.ExecuteScalarAsync<int>(sqlCount);

await Task.WhenAll(temtask,totaltask);

result.TotalCount=totalTask .result;
result.PagerList=tempTask.result;


标签: async await c#