WPF中未捕获异常之处理

来源:互联网 发布:http借口怎么写java 编辑:程序博客网 时间:2024/05/29 19:20

原帖地址:http://blog.csdn.net/luminji/article/details/5395595

异常有两类,一类是主线程异常,另一类是工作线程异常。

 

一:主线程的未捕获异常处理起来比较简单

1:首先在APP.XAML中定义一个DispatcherUnhandledException事件,如

[xhtml] view plaincopy
  1. <Application x:Class="CET.ExamViewer.App"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     StartupUri="WinMain.xaml"  
  5.     DispatcherUnhandledException="App_DispatcherUnhandledException" >  
  6.     <Application.Resources>  
  7.            
  8.     </Application.Resources>  
  9. </Application>  

 

2:其次,事件函数可以如下:

[c-sharp] view plaincopy
  1. void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)  
  2.         {  
  3.             StringBuilder stringBuilder = new StringBuilder();  
  4.             stringBuilder.AppendFormat("应用程序出现了未捕获的异常,{0}/n", e.Exception.Message);  
  5.             if (e.Exception.InnerException != null)  
  6.             {  
  7.                 stringBuilder.AppendFormat("/n {0}", e.Exception.InnerException.Message);  
  8.             }  
  9.             stringBuilder.AppendFormat("/n {0}", e.Exception.StackTrace);  
  10.             MessageBox.Show(stringBuilder.ToString());  
  11.             e.Handled = true;  
  12.         }  

 

 

二:工作线程异常的捕获

      对于工作线程的未捕获异常,也就是你主线程中,新起了一个线程,然后这个线程抛出的异常。如果你不做特殊处理,则光靠DispatcherUnhandledException是捕获不了的。

      所以,我们就要对工作线程的异常进行重新包装。事实上,也就是用到了WPF中的主线程的Dispatcher。如下代码:

[c-sharp] view plaincopy
  1. public void 工作函数()  
  2.         {  
  3.             try  
  4.             {  
  5.                 some code may be throw new Exception("我是工作线程的异常信息");                  
  6.             }  
  7.             catch (Exception ex)  
  8.             {  
  9.                 PageMain.GetInstance().Dispatcher.Invoke((MethodInvoker)delegate  
  10.                     {  
  11.                         throw ex;  
  12.                     });  
  13.             }  
  14.         }  

      注意,上面代码中的PageMain.GetInstance().Dispatcher,就是获取主线程(也即主页面的)的Dispatcher。PageMain.GetInstance()就是主页面的一个单例,想必大家都已经很清楚如何实现了。