C# WPF全局捕获异常 防止程序崩溃闪退

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace ClearWord
{
/// <summary>
/// App
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
RegisterEvents();
base.OnStartup(e);
}

private void RegisterEvents()
{
//Task线程内未捕获异常处理事件
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;//Task异常

//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
{
e.Handled = true;
}
}
private static void HandleException(Exception ex)
{
// MessageBox.Show("出错了,请与开发人员联系:"+ ex.Message);
//记录日志
Utils.LogWrite(ex);

}
}

}
//Utils.LogWrite
//读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
private static readonly ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
public static void LogWrite(Exception ex)
{
if (!Directory.Exists("Log"))
{
Directory.CreateDirectory("Log");
}
var now = DateTime.Now;
var logpath = @"Log" + now.Year + "" + now.Month + "" + now.Day + ".log";
var log = " ----------------------" + DateTime.Now + " -------------------------- "
+ ex.Message
+ " "
+ ex.InnerException
+ " "
+ ex.StackTrace
+ " ----------------------footer-------------------------- ";
try
{
//设置读写锁为写入模式独占资源,其他写入请求需要等待本次写入结束之后才能继续写入
LogWriteLock.EnterWriteLock();
File.AppendAllText(logpath, log);
}
finally
{
//退出写入模式,释放资源占用
LogWriteLock.ExitWriteLock();
}
}

转自:https://blog.csdn.net/awangdea99/article/details/110630449

原文地址:https://www.cnblogs.com/javalinux/p/14977864.html