1、找回Main入口
/// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { [STAThread] public static void Main() { App app = new App(); app.InitializeComponent(); app.Run(); } }
2、全局异常捕获
/// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { //UI线程未捕获异常处理事件(UI主线程) this.DispatcherUnhandledException += App_DispatcherUnhandledException; //非UI线程未捕获异常处理事件(例如自己创建的一个子线程) AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; //Task线程内未捕获异常处理事件 TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; base.OnStartup(e); } #region 全局日志处理 /// <summary> /// Task线程异常 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { Exception ex = e.Exception as Exception; OnExceptionHandler("Task异常:", ex); } /// <summary> /// 主线程异常 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { Exception ex = e.Exception as Exception; OnExceptionHandler("系统异常", ex); e.Handled = true; } /// <summary> /// 子线程异常 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; OnExceptionHandler("非UI线程异常:", ex); } /// <summary> /// 异常处理 封装写日志 /// </summary> /// <param name="ex"></param> private void OnExceptionHandler(string msg, Exception ex) { //GalaSoft.MvvmLight.Messaging.Messenger.Default.Send<bool>(false, "ShowLoading"); var errorMsg = msg; if (ex != null) { 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); } Log4Helper.Error(errorMsg);//自己封装的日志管理 } #endregion }
WPF知识点全攻略目录:https://www.cnblogs.com/kuangxiangnice/p/11040070.html