title: Catching exceptions in tasks
body: <p>My base ViewModel, implemented a couple years ago, provides this extension method for running tasks while keeping the UI responsive*:</p>
  
  <pre><code>protected void Work(Action job)
  {
      IsBusy = true;
      var stackTrace = new StackTrace();
      var task = Task.Factory.StartNew(job)
          .ContinueWith(failedTask =&gt; HandleException(failedTask, stackTrace), 
                        TaskContinuationOptions.OnlyOnFaulted)
          .ContinueWith(_ =&gt; { IsBusy = false; });
  }
  
  void HandleException(Task task, StackTrace stackTrace)
  {
      Dispatcher.BeginInvoke(
          () =&gt; { throw new Exception(task.Exception.InnerException.ToString() + 
                                      stackTrace); });
  }
  </code></pre>
  
  <p><code>IsBusy</code> is a property observed from the UI to display a progress bar.</p>
  
  <p>The idea behind <code>HandleExceptions</code> is that they are observed and then thrown in the UI thread, caught by a <code>try/catch</code> block in the <code>Main()</code> method and logged before displaying a friendly message to the user and safely closing the app. The stackTrace is passed so the log includes the caller information.</p>
  
  <p>However, I recently started getting reports of the application crashing without logging, nor friendly messages, with this Windows dialog:</p>
  
  <p><img src="https://i.stack.imgur.com/wQqAb.png" alt="crash"></p>
  
  <p>Looking at the Windows event log, we got this EventData:</p>
  
  <blockquote>
    <p>Application: xxxxApplication.Loader.exe</p>
    
    <p>Framework Version: v4.0.30319</p>
    
    <p>Description: The process was terminated due to an unhandled exception.</p>
    
    <p>Exception Info: System.AggregateException</p>
    
    <p>Stack: at System.Threading.Tasks.TaskExceptionHolder.Finalize()</p>
  </blockquote>
  
  <p>Am I doing anything wrong with <code>ContinueWith()</code>?</p>
  
  <p>Is it possible for task exceptions to somehow stay unobserved?</p>
  
  <hr>
  
  <p><sub>
  *: I know about <code>BackgroundWorker</code>. This probably seemed like a better idea at the time, or had additional benefits.
  </sub></p>