This is a follow-up to this question. I've also read Stephen Toub's "Tasks and Unhandled Exceptions" and I think I understand how tasks and exceptions work and what "observed task" means. I however cannot figure out how to tell if a Task
has been observed or not. Is that possible at all without using reflection?
I'd like to borrow @Noseratio's code as an example:
static async void Observe(Task task)
{
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);
}
If we could tell whether the task had been observed, this could be made simpler and more readable:
static async void Observe(Task task)
{
if (!task.WasObserved)
await task;
}
// ...
var task = DoSomething()
try
{
bool ready = await DoSomethingElse();
if (!ready)
return null;
var value = await DoThirdThing(); // depends on DoSomethingElse
return value + await task;
}
finally
{
Observe(task);
}