以下启用异步的代码是否容易导致死锁

bru*_*use 0 c# asynchronous task task-parallel-library async-await

    public async Task<Foo> Execute(int id)
    {
        var parameters = new { id};

        using (var con = new SqlConnection(this.connectionString))
        {
            await con.OpenAsync();

            return await con.QueryAsync<foo>(
                "dbo.uspGetMeFoo",
                parameters,
                commandType: CommandType.StoredProcedure,
                commandTimeout: int.Parse(ConfigurationManager.AppSettings["SqlCommandTimeout"]))
                .ContinueWith(task =>  task.Result.FirstOrDefault());
        }
    }
Run Code Online (Sandbox Code Playgroud)

在调用类中等待这个方法,其中 - 在一段时间之后 - 我想在不明确阻塞的情况下使用结果.

我可以解决这个问题不使用ContinueWith上述,通过返回Task<IEnumerable<Foo>>FirstOrDefault()调用代码这个代替.

从我所看到的上面的阻塞是臭的,更糟糕​​的将导致问题,可能是一个僵局.我对么?

Ser*_*rvy 5

调用Result已经完成的Task(你知道任务将在其继续触发时完成)不会导致死锁.

当任务需要能够在另一个线程/上下文上调度操作以便能够完成,但是该线程/上下文在结果上阻塞时,会导致死锁.由于任务已经完成,阻塞线程/上下文不可能阻止它完成.

也就是说,你可以轻松await完成任务而不是打电话ContinueWith.