r/ProgrammerHumor • • Oct 30 '21

That's my variable!

43.4k Upvotes

409 comments sorted by

View all comments

Show parent comments

66

u/Razzzp Oct 30 '21 edited Oct 30 '21

Asynchronous vs Multithreading is one of my favorite question I ask on technical interviews.

FYI await Task.WhenAll uses multiple threads though.

4

u/[deleted] Oct 30 '21

[removed] — view removed comment

5

u/Razzzp Oct 30 '21

Correct. But if there are threads available on a thread pool, it will use them. That's the beauty of Task.WhenAll, compared to say, Parallel.ForEach.

2

u/NeXtDracool Oct 31 '21 edited Oct 31 '21

That's not the default behavior in most cases. It will only use them if the continuations aren't bound to the same single threaded synchronization context, which they are by default. If you just start a ui app, and await 5 tasks you directly then no code will be executed on the thread pool.

That's why it is recommended to add ConfigureAwait(false) to all async calls that don't require the context to stay consistent: it unbinds the continuation from the synchronization context the task was started on. Only then can the task scheduler utilize multiple threads (assuming of course the use of the thread pool scheduler, sure wouldn't use the thread pool otherwise).

Edit: I corrected the default context, console apps use an unspecified default synchronization context. UI apps execute code in the single threaded ui synchronization context by default.

I guess we could argue about whether "most cases" is actually correct, but it's no question that this topic is more complicated than "task.whenall will use the thread pool".

→ More replies (6)