(Just a theoretical question - for non-gui apps)
Assuming I have this code with many awaits
:
public async Task<T> ConsumeAsync()
{
await A();
await b();
await c();
await d();
//..
}
Where each task can take a very short period of time ,
Question (again , theoretical)
There could be a situation where the overall time dealing with all those "releasing back threads" and "fetching threads back" ( red & green here :)
Is taking more time than a single thread which could done all the work with a small amount of delay ,
I mean , I wanted to be the most productive , but instead , since all those switches back and forth - I actually lost productivity.
Can such scenario occur ?
Yes, in theory. Not normally, in the real world.
In the common case, async
is used for I/O-bound operations, and the overhead of thread management is undetectable in comparison to them. Most of the time, asynchronous operations either take a very long time (compared to thread management) or are already completed (e.g., a cache). Note that async
has a "fast path" that kicks in if the operation is already completed, where it does not yield the thread.
For more information, see the Zen of Async and Async Performance.