Frank LaRosa
Frank LaRosa

Reputation: 3623

Does "await Task.CompletedTask" do anything?

I'm curious about this statement:

await Task.CompletedTask;

I know that it nominally doesn't do anything practical, but what I'm wondering is whether it actually causes the running function to exit, then resume at the statement after the await, or whether it truly does nothing and doesn't interrupt the thread at all.

This might make a difference in the sense that it would cause the current run loop to complete and resume, and if the run loop is the main thread it would mean that UI changes got committed.

The documentation doesn't explain it, and I can't figure out a good way to decide which it is.

Thanks, Frank

Upvotes: 2

Views: 728

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457057

whether it actually causes the running function to exit, then resume at the statement after the await, or whether it truly does nothing and doesn't interrupt the thread at all.

await will first test its awaitable to see if it is already complete, and if it is, it will continue executing synchronously.

If you want to force an asynchronous function to yield, then use await Task.Yield();. Side note: this should be extremely rare in production code, but it's sometimes useful for unit tests.

Upvotes: 5

Related Questions