1.概要 捕获全部线程的异常 试验,最终结果task的异常没有找到捕获方法
2.代码
2.1.试验1
2.1.1 试验结果
2.2 代码
2.2.1主程序代码
using NLog;
using System;
using System.Threading;
using System.Windows.Forms;namespace 异常监控
{static class Program{/// <summary>/// 应用程序的主入口点。/// </summary>[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());}}/// <summary>/// UI异常处理/// </summary>/// <param name="sender"></param>/// <param name="e"></param>static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e){ToolInfo.WriteRecord("SystemLog", "Main1", e.Exception.ToString());}/// <summary>/// 非UI异常处理/// </summary>/// <param name="sender"></param>/// <param name="e"></param>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 异常监控
{/// <summary>/// 通用方法工具类/// </summary>public static class ToolInfo{/// <summary>/// 文档记录/// </summary>/// <param name="path">文件路径</param>/// <param name="filename">文件名称</param>/// <param name="str">内容</param>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);}}
}