1

I had troubles with a Task that I used ContinueWith on. In the callback, I did not observe/handle the Exception when the first task was faulted. I found out what happens in this case here:
Proper way to use .ContinueWith for Tasks

Keep in mind that, if your own continuations don't observe the exception, the person who is waiting on this overall workflow to complete is going to be the one observe it.

Which made me wonder:
Who is the waiter of a Task that is not awaited?
Who is waiting for a Task by default?

For example:

public int HowOldAmI()
{
    Task t = Task.Run(async () => {
            await Task.Delay(5000); 
            throw new Exception("Something happened");
    });
    return 42;
}

In this case, who is waiting for the Task?

Community
  • 1
  • 1
Thibault D.
  • 10,041
  • 3
  • 25
  • 56
  • 3
    Nothing is, in the case you've shown. Nothing "implicitly" waits for a task to complete - if you choose to create a task and not wait for it, any exceptions go to the unobserved exception handler. – Jon Skeet Aug 22 '16 at 11:04
  • Ok thank you @JonSkeet. Is the _unobserved exception handler_ documented somewhere? The reason I'm asking is that my crash-reporting library is catching these exceptions although no real crash is happening, so I'm trying to handle the exceptions correctly so that they don't appear in my crash reports. – Thibault D. Aug 22 '16 at 11:19
  • 1
    See the answer from Andrew... – Jon Skeet Aug 22 '16 at 11:20

1 Answers1

2

Nothing is awaiting tasks that are, well, not awaited by anything. This is why it is important to await them, otherwise all those exceptions are going to be swallowed and you may not know that the program has a logical error in it. Earlier versions of .NET had different logic and caused the process to crash in case of unobserved exceptions.

There is also an event that helps with unobserved exceptions (e.g. to have them at least logged somewhere): TaskScheduler.UnobservedTaskException.

See also discussion in this question: Unobserved Task exceptions in .NET 4.5 still crash app

Community
  • 1
  • 1
Andrew Sklyarevsky
  • 2,095
  • 14
  • 17
  • Ok thank you. So the _UnobservedTaskException_ handler will be called, even if I continue my first `Task t` with `t.ContinueWith((previousTask) => { /* Code that does not observe the Exception */ });` ? – Thibault D. Aug 22 '16 at 11:22
  • 1
    Yes, exactly. You would need to access task's `Result` or `Exception` properties, or wait its result for exception to be `observed`. Otherwise, it will be passed through to that event. – Andrew Sklyarevsky Aug 22 '16 at 11:52