wpf 全局異常捕獲處理


namespace WpfGridChange
{
    using System;
    using System.CodeDom.Compiler;
    using System.Diagnostics;
    using System.Windows;
    using System.Threading.Tasks;

    public class App : Application
    {
        [DebuggerNonUserCode, GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        public void InitializeComponent()
        {
             base.StartupUri = new Uri("../Resources/xaml/WinWellcome.xaml", UriKind.Relative);
           
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            RegisterEvents();
            base.OnStartup(e);
        }

        /// <summary>
        /// 注冊事件
        /// </summary>
        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 + "\r\n@@" + Environment.NewLine + e.StackTrace + "\r\n##" + Environment.NewLine + e.Message);

            //記錄日志
            Utils.LogWrite(e);

        }


        [GeneratedCode("PresentationBuildTasks", "4.0.0.0"), DebuggerNonUserCode, STAThread]
        public static void Main()
{ App app
= new App(); app.InitializeComponent(); app.Run(); } } }

 

Utils.LogWrite
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Net;
using System.Threading;

namespace WpfGridChange
{
    public class Utils
    {

       
        //讀寫鎖,當資源處於寫入模式時,其他線程寫入需要等待本次寫入結束之后才能繼續寫入
        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 = "\r\n----------------------" + DateTime.Now + " --------------------------\r\n"
                      + ex.Message
                      + "\r\n"
                      + ex.InnerException
                      + "\r\n"
                      + ex.StackTrace
                      + "\r\n----------------------footer--------------------------\r\n";
            try
            {
                //設置讀寫鎖為寫入模式獨占資源,其他寫入請求需要等待本次寫入結束之后才能繼續寫入
                LogWriteLock.EnterWriteLock();
                File.AppendAllText(logpath, log);
            }
            finally
            {
                //退出寫入模式,釋放資源占用
                LogWriteLock.ExitWriteLock();
            }
        }


    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM