c# 捕获全部线程的异常 试验

1.概要 捕获全部线程的异常 试验,最终结果task的异常没有找到捕获方法

2.代码

2.1.试验1

2.1.1 试验结果

c# 捕获全部线程的异常 试验_第1张图片

 2.2 代码

2.2.1主程序代码

using NLog;
using System;
using System.Threading;
using System.Windows.Forms;

namespace 异常监控
{
    static class Program
    {
        /// 
        /// 应用程序的主入口点。
        /// 
        [STAThread]
        static void Main()
        {
            try
            {
                Logger Logger = LogManager.GetCurrentClassLogger();
                //设置应用程序处理异常方式:ThreadException处理
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            catch(Exception ex)
            {
                ToolInfo.WriteRecord("SystemLog", "Main", ex.ToString());
            }
                
        }
        /// 
        /// UI异常处理
        /// 
        /// 
        /// 
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            ToolInfo.WriteRecord("SystemLog", "Main1", e.Exception.ToString());
        }

        /// 
        /// 非UI异常处理
        /// 
        /// 
        /// 
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            ToolInfo.WriteRecord("SystemLog", "Main2", e.ExceptionObject.ToString());
        }
    }
}

 2.2.2窗口代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 异常监控
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            throw new Exception("dddd");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Task task = new Task(() =>
            {
                throw new Exception("dddd");
            });
            task.Start();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(() => {

                throw new Exception("dddd");
            });
            thread.Start();
        }
    }
}

2.2.3日志类 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 异常监控
{
    /// 
    /// 通用方法工具类
    /// 
    public static class ToolInfo
    {
       
        /// 
        /// 文档记录
        /// 
        /// 文件路径
        /// 文件名称
        /// 内容
        public static void WriteRecord(string path, string filename, string str)
        {
            DateTime nowTime = DateTime.Now;
            int nYear = nowTime.Year;
            int nMonth = nowTime.Month;
            int nDay = nowTime.Day;
            int nHour = nowTime.Hour;

            //创建记录文件名称
            string strDT = "";
            string strfilename = "";
            strDT = nowTime.Day.ToString() + nowTime.Hour.ToString();
            strfilename = string.Format(".\\{0}\\{1}-{2}.txt", path, filename, strDT);

            //删除文件名称
            for (int i = 1; i < nDay; i++)
            {
                for (int j = 1; j <= 24; j++)
                {
                    string strLYDT = "";
                    string strLYfilename = "";
                    strLYDT = i.ToString() + j.ToString();
                    strLYfilename = string.Format(".\\{0}\\{1}-{2}.txt", path, filename, strLYDT);
                    //删除今天之前的文件

                    if (File.Exists(strLYfilename))
                    {
                        File.Delete(strLYfilename);
                    }
                }
            }
            //记录内容
            string strData = "";
            strData = nowTime.ToString();
            strData += ": ";
            strData += str;
            strData += "\r\n";

            FileStream fs = new FileStream(strfilename, FileMode.Append);

            StreamWriter sw = new StreamWriter(fs);
            sw.Write(strData);
            sw.Flush();
            sw.Close();
            fs.Close();
        }
       
    }
}

2.2 试验2

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

            try
            {
                throw new Exception("1");
            }
            catch (Exception e)
            {
                Console.WriteLine("Catch clause caught : {0} \n", e.Message);
            }
            Task t = new Task(() =>
            {
                throw new Exception("2");
            });
            t.Start();
            Console.ReadKey();
            
        }
        static void MyHandler(object sender, UnhandledExceptionEventArgs args)
        {
            Exception e = (Exception)args.ExceptionObject;
            Console.WriteLine("MyHandler caught : " + e.Message);
            Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
        }
    }
}

2.3 试验3 监控主线程的异常

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

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // 创建一个新线程并抛出异常
            Thread thread = new Thread(DoSomething);
            thread.Start();

            // 主线程继续执行其他操作
            Console.WriteLine("主线程继续执行其他操作...");

            // 防止主线程退出
            Console.ReadLine();
        }
        static void DoSomething()
        {
            throw new Exception("线程抛出异常");
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            Console.WriteLine("捕获到异常:" + ex.Message);
        }
    }
}

你可能感兴趣的:(c#,c#,开发语言,异常捕获)