Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve "true" asynchrony

In his answer to this question, Stephen Cleary refers to "fake" asynchrony and "true" asynchrony.

there's a much easier way to schedule work to the thread pool: Task.Run.

True asynchrony isn't possible, because you have a blocking method that you must use. So, all you can do is a workaround - fake asynchrony, a.k.a. blocking a thread pool thread.

How then is it possible to achieve true asynchrony, like the various methods in System.Threading.Tasks.Task? Aren't all "truly asynchronous" methods just blocking operations on some other thread if you dig deep enough?

like image 806
rory.ap Avatar asked Dec 09 '22 04:12

rory.ap


1 Answers

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.

like image 80
i3arnon Avatar answered Jan 05 '23 00:01

i3arnon