async var for easy and safe parallelism #4235
Unanswered
YairHalberstadt
asked this question in
General
Replies: 1 comment
-
I don't understand, why are you working so hard to avoid |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Problem
async/await
makes it easy to avoid blocking a thread whilst waiting for some task to complete, and it looks like it should make parallelism easy too. You just kick of all the tasks you can, and then await them at some point in the future, once you've done everything else you can. For example:Unfortunately it's not so simple as this. What happens if
PrepVegetables
throw for example? Then you will neverawait
thedessertArrivalTask
or thepreheatOvenTask
. This can theoretically lead to anUnobservedTaskException
which is generally considered a bad thing - so bad in fact that in the past it used to crash the application.So next stage is this:
This is already bad enough, but it can get worse. What happens if our original sample had an existing try block which stops us putting the try blocks we need to add where they should be, and we were using
ValueTask
s (this is the exact scenario in my IOC source generator), like so:Remember we can't use
ValueTask
s after they've been awaited so now we need to track whether we've awaited them:This is not really practical to do (outside source generators), so either people don't bother, and let the UnobservedTaskException trigger, or just don't bother with parallelism and make the whole thing linear.
Suggested Solution:
async var
This is inspired by swift's proposed model for concurrency: https://forums.swift.org/t/concurrency-structured-concurrency/41622
A
var
can be marked asasync var
like so:An
async var
must have a suitableGetAwaiter
method as usual, but theAwaiter
must have a method or extension methodvoid CancelOrIgnore()
. Anasync var
can only be awaited. It can not be used in any other fashion.The compiler will generate code such that on any code path where a variable assigned to an
async var
is notawaited
,.GetAwaiter().CancelOrIgnore()
will be called instead.Beta Was this translation helpful? Give feedback.
All reactions