Aren't all "truly asynchronous" methods just blocking operations on some other thread if you dig deep enough?
No. Truly asynchronous operations don't need a thread throughout the entire operation and using one limits scalability and hurts performance.
While most truly asynchronous operations are I/O ones, that can get too overly complicated to understand. (For a deep dive read There Is No Thread by Stephen Cleary).
Let's say for example that you want to await
a user's button click. Since there's a Button.Click
event we can utilize TaskCompletionSource
to asynchronously wait for the event to be raised:
var tcs = new TaskCompletionSource<bool>();
_button.Click += (sender, EventArgs e) => tcs.SetResult(false);
await tcs.Task;
There's no non-generic TaskCompletionSource
so I use a bool
one with a dummy value. This creates a Task
which isn't connected to a thread, it's just a synchronization construct and will only complete when the user clicks that button (through SetResult
). You can await
that Task
for ages without blocking any threads whatsoever.
Task.Delay
for that matter is implemented very similarly with a System.Threading.Timer
that completes the awaited task in its callback.