0

For some reason unhandled exception which occur at non-UI thread don't handled by App_UnhandledException handler.

This approach works well for Windows Phone apps to globally handle, track and analyze exceptions but doesn't work for Windows 8 apps.

this.UnhandledException += App_UnhandledException; //doesn't handle

private void Button_Click_1(object sender, RoutedEventArgs e)

{
   var task = new Task(() => { throw new NullReferenceException("Test exc in UI thread"); });
   task.Start();
}

Please, advise.

Mando
  • 11,414
  • 17
  • 86
  • 167

2 Answers2

0

Using the new async/await keywords:

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    var task = new Task(() => { throw new NullReferenceException("Test exc in UI thread"); });
    task.Start();
    try
    {
        await task;
    }
    catch (Exception ex)
    {
        var msg = new MessageDialog(ex.ToString(), "An error has occurred");
        await msg.ShowAsync();
    }
}

Using just the Task methods:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    var task = new Task(() => { throw new NullReferenceException("Test exc in UI thread"); });
    task.ContinueWith(t =>
    {
        var msg = new MessageDialog(t.Exception.ToString(), "An error has occurred");
        msg.ShowAsync().Start();
    }, TaskContinuationOptions.OnlyOnFaulted);
    task.Start();
}

For catching all unhandled exceptions, see this question:

Community
  • 1
  • 1
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
  • I don't have Win8 for another week, but I'm *pretty* sure you should pass `TaskScheduler.FromCurrentSynchronizationContext` to `ContinueWith`. – Stephen Cleary Oct 07 '12 at 00:19
0

Using the UnobservedTaskException event of TaskScheduler you can catch all exceptions in Tasks that are not awaited. Just to clarify: If you await tasks exceptions are propagated to the UI thread and can hence be catched via Application.UnhandledException.

Jürgen Bayer
  • 2,993
  • 3
  • 26
  • 51