Dapper QueryAsync消息返回任务已取消

时间:2018-08-13 07:39:07

标签: c# asynchronous dapper

我在dapper和异步方法时出错。我在做什么错了?

这是我的代码。

public Task<IEnumerable<Student>> GetStudentsAsync(int type)
{
    var sql = "[dbo].[StudentController_GetStudents]";

    var students = Connection.QueryAsync<Student>(sql,
        new
        {
            type
        },
        commandType: CommandType.StoredProcedure
    );

    return students;
}

public Task<IEnumerable<Teacher>> GetTeachersAsync(int type)
{
    var sql = "[dbo].[StudentController_GetTeachers]";

    var teachers = Connection.QueryAsync<Teacher>(sql,
        new
        {
            type
        },
        commandType: CommandType.StoredProcedure,
    );

    return teachers;
}


var studentsTask = StudentDao.GetStudentsAsync(type);

var teachersTask = StudentDao.GetTeachersAsync(type);


UpdateStudents(await studentsTask);

UpdateTeachers(await teachersTask);

调用“ await教师任务”时出现错误,堆栈跟踪错误为:

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Dapper.SqlMapper.<QueryAsync>d__23`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

有人可以告诉我我在做什么错吗?我想同时执行两个查询,然后等待结果。 我知道与SQL连接有关的东西未打开或有东西,但不知道如何解决。

谢谢。

1 个答案:

答案 0 :(得分:0)

使用此私有方法打开与SQL的连接,并使用GetStudents吸引学生,老师也一样。

    private SqlConnection GetConnection()
    {
        return new SqlConnection("ConnectionString");
    }

    public async Task<IEnumerable<Student>> GetStudentsAsync(int type)
    {
        using (var connection = GetConnection())
        {  
            DynamicParameters param = new DynamicParameters();
                param.Add("@type", type);
            var result = await connection.QueryAsync<Student>("[dbo].[StudentController_GetStudents]",param, commandType: CommandType.StoredProcedure);
            return result.ToList();
        }
    }

  public async Task<IEnumerable<Teacher>> GetTeachersAsync(int type)
    {
        using (var connection = GetConnection())
        {  
            DynamicParameters param = new DynamicParameters();
                param.Add("@type", type);
            var result = await connection.QueryAsync<Student>("[dbo].[StudentController_GetTeachers]",param, commandType: CommandType.StoredProcedure);
            return result.ToList();
        }
    }

UpdateStudents(await StudentDao.GetStudentsAsync(type));

UpdateTeachers(await StudentDao.GetTeachersAsync(type));