Home > OS >  Can an awaited Task return false in IsCompleted
Can an awaited Task return false in IsCompleted

Time:11-09

I found this piece of code:

Task task = DoSomethingAsync( someObject );
await task.ConfigureAwait( false );
if ( task.IsCompleted ){ ... }

I wonder if I can safely replace it with

await DoSomethingAsync( someObject ).ConfigureAwait( false );

and drop the if clause.

My question: can task.IsCompleted ever be false when an awaited task has returned?

The documentation of IsCompleted tells us:

true if the task has completed (that is, the task is in one of the three final states: RanToCompletion, Faulted, or Canceled); otherwise, false.

I looked up the possible states but it is still not clear to me which of the states is possible when the awaited task hast returned.

Please help me to shed light on this matter. Thanx in advace.

CodePudding user response:

Docs: await operator (C# reference)

The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes.

After Task taskInstance = ...; await taskInstance;, taskInstance.IsCompleted will always be true.

CodePudding user response:

Based on this article: https://profinit.eu/en/blog/lets-dive-into-async-await-in-c-part-3/ the example that you found is a bad approach. So you can use safely the version:

await DoSomethingAsync( someObject ).ConfigureAwait( false );

You can omit ConfigureAwait(false) but depends on the context where you use the method DoSomethingAsync.

  • Related