In the context of ASP.NET, why doesn't Task.Run(…).Result deadlock when calling an async method?

前端 未结 2 792
青春惊慌失措
青春惊慌失措 2021-02-06 13:37

I created a simple WebApi project with a single controller and a single method:

public static class DoIt
{
    public static async Task GetStrAsync         


        
2条回答
  •  抹茶落季
    2021-02-06 14:04

    Result by itself isn't going to cause a deadlock. A deadlock is when two parts of the code are both waiting for each other. A Result is just one wait, so it can be part of a deadlock, but it doesn't necessarily always cause a deadlock.

    In the standard example, the Result waits for the task to complete while holding onto the context, but the task can't complete because it's waiting for the context to be free. So there's a deadlock - they're waiting for each other.

    ASP.NET Core does not have a context at all, so Result won't deadlock there. (It's still not a good idea for other reasons, but it won't deadlock).

    The problem is this is not deadlocking, and it's giving me heart palpitations.

    This is because the Task.Run task does not require the context to complete. So calling Task.Run(...).Result is safe. The Result is waiting for the task to complete, and it is holding onto the context (preventing any other parts of the request from executing in that context), but that's OK because the Task.Run task doesn't need the context at all.

    Task.Run is still not a good idea in general on ASP.NET (for other reasons), but this is a perfectly valid technique that is useful from time to time. It won't ever deadlock, because the Task.Run task doesn't need the context.

    However, there are similar questions to mine asking why the above code does deadlock,

    Similar but not exact. Take a careful look at each code statement in those questions and ask yourself what context it runs on.

    and I've seen deadlocks occur in cases where ConfigureAwait(false) is used (not capturing the context) in conjunction with .Result.

    The Result/context deadlock is a very common one - probably the most common one. But it's not the only deadlock scenario out there.

    Here's an example of a much more difficult deadlock that can show up if you block within async code (without a context). This kind of scenario is much more rare, though.

提交回复
热议问题