Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Check task state after await

Tags:

c#

task

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

like image 487
Moerwald Avatar asked Feb 17 '26 23:02

Moerwald


1 Answers

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 ;)

like image 51
TomTom Avatar answered Feb 19 '26 11:02

TomTom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!