当前位置: 移动技术网 > 科技>操作系统>windows > winform或wpf中全局异常捕获

winform或wpf中全局异常捕获

2020年04月22日  | 移动技术网科技  | 我要评论

传说中的绝杀技找谁,torrent 文件,李琛琛留言

winform或者wpf项目中难免会遇到忘记捕获的异常的代码块,c#为我们提供了全局捕获异常的机制

winform中在program.cs中这样写

   static class program
   {      
[stathread] static void main() {
application.setunhandledexceptionmode(unhandledexceptionmode.catchexception); //ui线程异常 application.threadexception += application_threadexception; //非ui线程异常 appdomain.currentdomain.unhandledexception += currentdomain_unhandledexception;

application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); application.run(new formmain());
} private static void currentdomain_unhandledexception(object sender, unhandledexceptioneventargs e) { //log.error or messagebox.show } private static void application_threadexception(object sender, system.threading.threadexceptioneventargs e) { //log.error or messagebox.show } }

wpf中在app.xaml.cs这样写

    public partial class app : application
    {
        public app()
        { 
            //ui线程异常
            this.dispatcherunhandledexception += app_dispatcherunhandledexception;
            //非ui线程异常
            appdomain.currentdomain.unhandledexception += currentdomain_unhandledexception;
        }
        private void currentdomain_unhandledexception(object sender, unhandledexceptioneventargs e)
        {
            //log.error or messagebox.show
        }
        private void app_dispatcherunhandledexception(object sender, system.windows.threading.dispatcherunhandledexceptioneventargs e)
        {
            //log.error or messagebox.show
        }
     }

我们可以在异常回调里面弹窗提示或者记录日志

这样写可以捕获大部分异常信息,但是有些应用场景例外

比如我们使用[dllimport("xxx.dll")]调用c\c++写的方法时,无法捕获异常导致程序卡死或者闪退

我们可以尝试用[handleprocesscorruptedstateexceptions]特性

[handleprocesscorruptedstateexceptions]
public void dosomething()
{
      try
      {
          test(1, 2);
      }
      catch(exception ex)
      {
         //log or messagebox.show
      }
}
[dllimport("xxx.dll")]
public static extern int test(int a,int b);

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网