Zeus82
Zeus82

Reputation: 6375

Can a TaskCanceledException mean a Deadlock has occurred?

I am working on making one of our applications async, and now my HttpClient is timing out (I get a TaskCanceledException) when I call SendAsync. Here is the code that's timing out:

            response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
                .ConfigureAwait(false);

From what I understand, ConfigureAwait(false) means that I can't deadlock this task. I am awaiting for this all the way up(or down) the stack.

When I make the same request in postman it takes will under a second. The timeout for my HttpClient is 2 minutes. Could there be something else going on?

Also, because I am getting a TaskCanceledException does that mean that my Tasks are not deadlocked?

Update

Thanks for the answer @Servy, I have managed to get around my problem by changing the above code to:

            response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
                .ConfigureAwait(false).GetAwaiter().GetResult();

So if I don't await it, everything works properly. Does this mean that it is most likely a deadlock somewhere?

Upvotes: 3

Views: 653

Answers (1)

Servy
Servy

Reputation: 203830

From what I understand, ConfigureAwait(false) means that I can't deadlock this task.

That's not true. You get a deadlock anytime you're synchronously waiting on your synchronization context on an asynchronous operation that's trying to execute a continuation on that same synchronization context. That this one continuation isn't trying to use the synchronization context doesn't meant that there isn't some other continuation somewhere else that is. So while we know that this one await isn't what's causing the deadlock, it doesn't mean there isn't one.

I am awaiting for this all the way up(or down) the stack.

If this is true, and there is nothing synchronously blocking the synchronization context then that would mean you don't have a deadlock in your code. (Or at least, not this common source of a deadlock.)

When I make the same request in postman it takes will under a second. The timeout for my HttpClient is 2 minutes. Could there be something else going on?

Sure. A firewall could be getting in the way, your network cord could have come unplugged, the other site could be offline, or intentionally ignoring your requests for some reason.

Also, because I am getting a TaskCanceledException does that mean that my Tasks are not deadlocked?

It doesn't really tell you either way. If the specific operation that's trying to schedule a continuation on a blocked synchronization context also has a cancellation token that results in it timing out after a while, then it'd deadlock until it was cancelled. But there are of course any number of things that could result in a Task being cancelled without there being a deadlock.

Upvotes: 3

Related Questions