Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

public static class DoIt
{
    public static async Task<string> GetStrAsync(Uri uri)
    {
        using (var client = new HttpClient())
        {
            var str = await client.GetStringAsync(uri);
            return str;
        }
    }
}

public class TaskRunResultController : ApiController
{
    public string Get()
    {
        var task = Task.Run(() =>
            DoIt.GetStrAsync(new Uri("http://google.com"))
        );
        var result = task.Result;

        return result;
    }
}

I have a good understanding of async/await and tasks; almost religiously following Stephen Cleary. Just the existence of .Result makes me anxious, and I expect this to deadlock. I understand that the Task.Run(...) is wasteful, causing a thread to be occupied while waiting for the async DoIt() to finish.

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

I see some answers like https://stackoverflow.com/a/32607091/1801382, and I've also observed that SynchronizationContext.Current is null when the lambda is executing. However, there are similar questions to mine asking why the above code does deadlock, and I've seen deadlocks occur in cases where ConfigureAwait(false) is used (not capturing the context) in conjunction with .Result.

What gives?

like image 841
aholmes Avatar asked Jun 29 '17 00:06

aholmes


1 Answers

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.

like image 57
Stephen Cleary Avatar answered Oct 05 '22 08:10

Stephen Cleary