Consider this example:
var task = DoSomething()
bool ready = await DoSomethingElse();
if (!ready)
return null;
var value = await DoThirdThing(); // depends on DoSomethingElse
return value + await task;
DoSomething
does some very important work that may take a while, thus we start it off first.
In the meantime we check whether we're ready with DoSomethingElse
and exit early if not.
We call DoThirdThing
only if we are ready
, as the universe might otherwise explode.
We cannot use Task.WhenAll
as DoThirdThing
depends on DoSomethingElse
and we also don't want to wait for DoSomething
because we want to call the other two methods concurrently if possible.
The question: What happens to task
if we're not ready
and exit early?
Will any exceptions that it throws be re-thrown by a SynchronizationContext
?
Are there problems if task
completes normally, as nobody consumes its value?
Follow-up: Is there a neat way to make sure task
is awaited?
We could simply await task
if we are not ready
, however if there were 50 exit conditions this would be very tedious.
Could a finally
block be used to await task
and re-throw potential exceptions? If task
completed normally it would be awaited again in the finally
block, but that shouldn't cause any problems?