wpf捕捉全局异常

1、在App.xaml.cs文件中添加以下代码

    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// 设置程序单例运行
        /// </summary>
        private static Mutex mutex;
        protected override void OnStartup(StartupEventArgs e)
        {
            mutex = new Mutex(true, "Channel", out bool ret);
            if (!ret)
            {
                MessageBox.Show("程序已经打开");
                Environment.Exit(0);
            }
            base.OnStartup(e);
            RegisterEvents();
        }

        /// <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)
        {
            //将异常信息写入到日志文件
            FileUtil.Log(e.ToString());
        }
    }

2、日志文件操作

    class FileUtil
    {
        public string filePath;

        // #region API函数声明
        [DllImport("kernel32")]//返回0表示失败,非0为成功
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        //  #endregion

        public FileUtil(string filePath)
        {
            if (File.Exists(filePath))
            {
                this.filePath = filePath;
            }
            else
            {
                FileStream fs = File.Create(filePath);
                fs.Close();
                this.filePath = filePath;
            }
        }
        /// <summary>
        /// 读
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public string Read(string section, string key, string def)
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(section, key, def, temp, 1024, filePath);
            return temp.ToString();
        }
        /// <summary>
        /// 写
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool Write(string section, string key, string value)
        {
            long OpStation = WritePrivateProfileString(section, key, value, filePath);
            if (OpStation == 0)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="text"></param>
        public static void Log(string text)
        {
            string[] nowRes = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Split(new char[] { ' ' });
            string logFile = @"Log\" + nowRes[0] + ".log";
            if (!Directory.Exists("Log"))
            {
                Directory.CreateDirectory("Log");
            }
            File.AppendAllText(logFile, "[" + nowRes[1] + "] " + text + "\r\n");
        }
    }

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值