2012-10-06 46 views
0

由于某些原因,在非UI线程中发生的未处理的异常不由App_UnhandledException处理程序处理。在非UI线程中处理错误

此方法适用于Windows Phone应用程序全局处理,跟踪和分析异常,但不适用于Windows 8应用程序。

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(); 
} 

请指教。

回答

0

使用TaskScheduler的UnobservedTaskException事件,可以捕获任务中未等待的所有异常。只是澄清:如果您等待任务异常传播到UI线程,并因此可以通过Application.UnhandledException捕获。

+0

非常感谢!这正是我需要的 –

0

使用新async/await关键字:

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(); 
    } 
} 

只需使用Task方法:

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(); 
} 

为了捕捉所有未处理的异常,看到了这个问题:

+0

我没有Win8的另一周,但我很* *确定你应该将'TaskScheduler.FromCurrentSynchronizationContext'传递给'ContinueWith'。 –