WinForm代码
private void button1_Click(object sender, EventArgs e)
{
try
{
Convert.ToInt32("abcd");
}
catch (Exception ex)
{
///通过delegate转向工作线程的异常处理
new ThreadExceptionHelper().ExceptionHandler(ex);
}
}
处理代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace WinFormTest
{
public class ThreadExceptionHelper
{
/// <summary>
/// 通过delegate转向工作线程的异常处理
/// </summary>
/// <param name="ex"></param>
public void ExceptionHandler(Exception ex)
{
new WorkerThreadExceptionHandlerDelegate(WorkerThreadExceptionHandler).BeginInvoke(ex, null, null);
} public void MainUIThreadExceptionHandler(Exception ex)
{
MainUIThreadExceptionHandler(this, new ThreadExceptionEventArgs(ex));
} /// <summary>
/// 主线程全局异常信息的处理
/// </summary>
/// <param name="sender"></param>
/// <param name="t"></param>
public static void MainUIThreadExceptionHandler(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show("系统异常:" + e.Exception.Message, "异常信息", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
} /// <summary>
/// 声明工作线程的delegate
/// </summary>
public delegate void WorkerThreadExceptionHandlerDelegate(Exception e); /// <summary>
/// 工作线程的异常处理
/// </summary>
/// <param name="e"></param>
public void WorkerThreadExceptionHandler(Exception e)
{
///添加其他的处理代码 ///通知全局异常处理程序
MainUIThreadExceptionHandler(this, new System.Threading.ThreadExceptionEventArgs(e));
}
}
}