3

Saw kind of this code in production:

var task = new HttpClient().GetAsync(u);
var response = await task;
if (task.IsCompletedSuccessfully)
{
   Console.WriteLine($"Task is faulted: {task}");
}

Question: Does it make any sense to check the Task state after the await keyword? As far as I know, the compiler will build a state-machine "around" this code, which throws an exception in case of an error. Based on that it won't make any sense to check the Tasks state.

Am I missing something?

Thanks

Moerwald
  • 10,448
  • 9
  • 43
  • 83
  • Don't create new `HttpClient` per request, refer to the [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#examples). `HttpResponseMessage` is `IDisposable`, it's important, implement `using`. You may not check `Task.IsCompletedSuccessfully` here but check `response.IsCompletedSuccessfully` , it will check if there HTTP 200 or something else. As alternative way you may throw an exception with method `response.EnsureSuccessStatusCode()`. – aepot Jul 12 '20 at 10:39
  • Here's some [POST example](https://stackoverflow.com/a/62802872/12888024) but, GET is almost the same. – aepot Jul 12 '20 at 10:51
  • Without the await, is (task.IsCompletedSuccessfully) blocking? – variable Jul 30 '21 at 18:10

1 Answers1

6

Nope.

If there is an exception, then await will throw it. It wil lbasically not return the task, but the return value or throw the exception.

As such, there is no sense in evaluating the task further.

Otherwise the gain from await would be quite insignificant ;)

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • Note: `HttpResponseMessage` will not throw on HTTP response errors. – aepot Jul 12 '20 at 10:55
  • 1
    But that is not because of the task - it is because those are not exceptions. They are valid responses that contain an error and thus must be evaluated. Yes, I got an answer, but the answer may be a 404 or a 301. – TomTom Jul 12 '20 at 11:11