应用启动入口
这里响应启动事件 Startup="Application_Startup"
处理初始化数据
// App.xaml <Application x:Class="MRLGauger_Programmer.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MRLGauger_Programmer" StartupUri="MainWindow.xaml" Startup="Application_Startup"> <Application.Resources> </Application.Resources> </Application>
using System.Windows.Threading;
// app.xaml.cs private void Application_Startup(object sender, StartupEventArgs e) { // Application.Current.StartupUri = new Uri("TestWindow.xaml", UriKind.Relative);
//UI线程未捕获异常处理事件(UI主线程) DispatcherUnhandledException += App_DispatcherUnhandledException; //非UI线程未捕获异常处理事件(例如自己创建的一个子线程) AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; //Task线程内未捕获异常处理事件 TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; }
//UI线程未捕获异常处理事件(UI主线程) private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { string msg = String.Format("{0}\n\n{1}", e.Exception.Message, e.Exception.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异常"); }
|