[WPF]WPF全局异常处理
WPF全局异常处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace WpfApplication1 { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { private void Application_Startup( object sender, StartupEventArgs e) { Application.Current.StartupUri = new Uri( "TestWindow.xaml" ,UriKind.Relative); //UI线程未捕获异常处理事件(UI主线程) this .DispatcherUnhandledException += App_DispatcherUnhandledException; //非UI线程未捕获异常处理事件(例如自己创建的一个子线程) AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; //Task线程内未捕获异常处理事件 TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; } //UI线程未捕获异常处理事件(UI主线程) private void App_DispatcherUnhandledException( object sender, DispatcherUnhandledExceptionEventArgs e) { Exception ex = e.Exception; string msg = String.Format( "{0}\n\n{1}" , ex.Message, ex.StackTrace); //异常信息 和 调用堆栈信息 MessageBox.Show(msg, "UI线程异常" ); e.Handled = true ; //表示异常已处理,可以继续运行 } //非UI线程未捕获异常处理事件(例如自己创建的一个子线程) //如果UI线程异常DispatcherUnhandledException未注册,则如果发生了UI线程未处理异常也会触发此异常事件 //此机制的异常捕获后应用程序会直接终止。没有像DispatcherUnhandledException事件中的Handler=true的处理方式,可以通过比如Dispatcher.Invoke将子线程异常丢在UI主线程异常处理机制中处理 private void CurrentDomain_UnhandledException( object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; if (ex != null ) { string msg = String.Format( "{0}\n\n{1}" , ex.Message, ex.StackTrace); //异常信息 和 调用堆栈信息 MessageBox.Show(msg, "非UI线程异常" ); } } //Task线程内未捕获异常处理事件 private void TaskScheduler_UnobservedTaskException( object sender, UnobservedTaskExceptionEventArgs e) { Exception ex = e.Exception; string msg = String.Format( "{0}\n\n{1}" , ex.Message, ex.StackTrace); MessageBox.Show(msg, "Task异常" ); } //异常处理 封装 private void OnExceptionHandler(Exception ex) { if (ex != null ) { string errorMsg = "" ; if (ex.InnerException != null ) { errorMsg += String.Format( "【InnerException】{0}\n{1}\n" ,ex.InnerException.Message,ex.InnerException.StackTrace); } errorMsg += String.Format( "{0}\n{1}" , ex.Message, ex.StackTrace); LogManager.ErrorLog(errorMsg); //自己封装的日志管理 } } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?