Consider this example:
var task = DoSomething()
bool ready = await DoSomethingElse();
if (!ready)
return null;
var value = await DoThirdThing(); // depends o
Follow-up: Is there a neat way to make sure task is awaited?
If you need individual, more fine-grained than TaskScheduler.UnobservedTaskException
control over exceptions thrown by the tasks you don't await
, there is a handy tool for that: async void
methods.
Your code might look like this:
static async void Observe(Task task)
{
// use try/catch here if desired so;
// otherwise, exceptions will be thrown out-of-band, i.e.
// via SyncronizationContext.Post or
// via ThreadPool.QueueUSerWorkItem (if there's no sync. context)
await task;
}
// ...
var taskObserved = false;
var task = DoSomething()
try
{
bool ready = await DoSomethingElse();
if (!ready)
return null;
var value = await DoThirdThing(); // depends on DoSomethingElse
taskObserved = true;
return value + await task;
}
finally
{
if (!taskObserved)
Observe(task);
}
Some more details can be found here and here.