using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace lss
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
RegisterEvents();
}
//*********************************************************************************
private void RegisterEvents()
{
//Task线程内未捕获异常处理事件
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
//UI线程未捕获异常处理事件(UI主线程)
this.DispatcherUnhandledException += App_DispatcherUnhandledException;
//非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
try
{
var exception = e.Exception as Exception;
if (exception != null)
{
HandleException(exception);
}
}
catch (Exception ex)
{
HandleException(ex);
}
finally
{
e.SetObserved();
}
}
//非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
var exception = e.ExceptionObject as Exception;
if (exception != null)
{
HandleException(exception);
}
}
catch (Exception ex)
{
HandleException(ex);
}
finally
{
//ignore
}
}
//UI线程未捕获异常处理事件(UI主线程)
private static void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
try
{
HandleException(e.Exception);
}
catch (Exception ex)
{
HandleException(ex);
}
finally
{
//处理完后,我们需要将Handler=true表示已此异常已处理过
e.Handled = true;
}
}
private static void HandleException(Exception e)
{
MessageBox.Show("程序异常:" + e.Source + "@@" + Environment.NewLine + e.StackTrace + "##" + Environment.NewLine + e.Message);
//记录日志
// Utils.LogWrite(e);
}
//*********************************************************************************
}
}
WPF捕获全局异常
最新推荐文章于 2024-07-23 09:32:48 发布