My base ViewModel, implemented a couple years ago, provides this extension method for running tasks while keeping the UI responsive*:
protected void Work(Action job)
{
IsBusy = true;
var stackTrace = new StackTrace();
var task = Task.Factory.StartNew(job)
.ContinueWith(failedTask => HandleException(failedTask, stackTrace),
TaskContinuationOptions.OnlyOnFaulted)
.ContinueWith(_ => { IsBusy = false; });
}
void HandleException(Task task, StackTrace stackTrace)
{
Dispatcher.BeginInvoke(
() => { throw new Exception(task.Exception.InnerException.ToString() +
stackTrace); });
}
IsBusy is a property observed from the UI to display a progress bar.
The idea behind HandleExceptions is that they are observed and then thrown in the UI thread, caught by a try/catch block in the Main() 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.
However, I recently started getting reports of the application crashing without logging, nor friendly messages, with this Windows dialog:

Looking at the Windows event log, we got this EventData:
Application: xxxxApplication.Loader.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AggregateException
Stack: at System.Threading.Tasks.TaskExceptionHolder.Finalize()
Am I doing anything wrong with ContinueWith()?
Is it possible for task exceptions to somehow stay unobserved?
*: I know about BackgroundWorker. This probably seemed like a better idea at the time, or had additional benefits.
I would suggest you handle the AppDomain.CurrentDomain.UnhandledException
to either display your “friendly message” or (if this is not a solution for you) you could at least log the errors within this event and then see what the stacktrace is to determine where this “un-handled” task exception occurs.