title: Best strategy for finding tasks with unobserved exceptions
body: <p>Suppose I have the following code:</p>
  
  <pre><code>private static void Run()
  {
      TaskScheduler.UnobservedTaskException += delegate { Console.WriteLine("Unobserved task exception!"); };
  
      try
      {
          RunAsync().Wait();
      }
      catch (Exception)
      {
      }
  
      GC.Collect();
      GC.WaitForPendingFinalizers();
      GC.Collect();
  
      Thread.Sleep(Timeout.InfiniteTimeSpan);
  }
  
  private static async Task RunAsync()
  {
      var task1 = ThrowAsync();
      var task2 = ThrowAsync();
  
      await task1;
      await task2;
  }
  
  private static async Task ThrowAsync()
  {
      throw new Exception("Test exception");
  }
  </code></pre>
  
  <p>This code outputs <code>Unobserved task exception!</code> because the exception in <code>task2</code> is not observed.</p>
  
  <p>My question is the following: is there any way to programmatically determine which task had an unobserved exception? For example, I want to get a stack trace for a method which invoked a task or something like this:</p>
  
  <pre><code>Unobserved exception: task2 in RunAsync()
  </code></pre>
  
  <p>Sadly, exception stack trace is not enough. The code above is just a demonstration, in a real-world application I sometimes have unobserved task exceptions with a stack trace like this:</p>
  
  <pre><code>System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---&gt; System.NullReferenceException: Object reference not set to an instance of an object.
     at System.Web.HttpApplication.get_CurrentModuleContainer()
     at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)
  </code></pre>