title: Why is UnobservedTaskException thrown despite the observation when using async await?
body: <p>The following scenario runs under <em>.NET 4.5</em> so any <code>UnobservedTaskException</code> does not <a href="https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.unobservedtaskexception(v=vs.110).aspx" rel="nofollow noreferrer">terminate the process</a>.</p>
  
  <p>I have the habit of listening to any <code>UnobservedTaskException</code> thrown by having this execute at the start of my app:</p>
  
  <pre><code>private void WatchForUnobservedTaskExceptions()
  {
    TaskScheduler.UnobservedTaskException += (sender, args) =&gt;
    {
        args.Exception.Dump("Ooops");
    };
  }
  </code></pre>
  
  <p>I also have a helper method for when I want to <em>explicitly</em> ignore any exceptions thrown by my tasks:</p>
  
  <pre><code>public static Task IgnoreExceptions(Task task) 
    =&gt; task.ContinueWith(t =&gt;
        {
            var ignored = t.Exception.Dump("Checked");
        },
        CancellationToken.None,
        TaskContinuationOptions.ExecuteSynchronously,
        TaskScheduler.Default);
  </code></pre>
  
  <p>So if I have the following code execute:</p>
  
  <pre><code>void Main()
  {
    WatchForUnobservedTaskExceptions();
  
    var task = Task.Factory.StartNew(() =&gt;
    {
        Thread.Sleep(1000);
        throw new InvalidOperationException();
    });
  
    IgnoreExceptions(task);
  
    GC.Collect(2);
    GC.WaitForPendingFinalizers();
  
    Console.ReadLine();    
  }
  </code></pre>
  
  <p>After we return from the <code>Console.ReadLine()</code> we will not see any <code>UnobservedTaskException</code> thrown which is what we expect.</p>
  
  <p>However if I change the above <code>task</code> to start using <code>async/await</code> with everything else the same as before:</p>
  
  <pre><code>var task = Task.Factory.StartNew(async () =&gt;
  {
      await Task.Delay(1000);
      throw new InvalidOperationException();
  });
  </code></pre>
  
  <p>Now we get the <code>UnobservedTaskException</code> thrown. Debugging the code reveals the continuation executes with the  <code>t.Exception</code> being <code>null</code>.</p>
  
  <p>How can I ignore the exceptions properly in both scenarios?</p>