Application.ThreadException事件 [英] Application.ThreadException Event

查看:81
本文介绍了Application.ThreadException事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#MS文档中有一个示例,说明了如何使用它来捕获未处理的事件.它提出了代码:

There is an example in the C# MS documentation that explains how to use this to capture unhandled events. It proposes the code:

Thread newThread = null;
// Starts the application. 
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{
    // Add the event handler for handling UI thread exceptions to the event.
    Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
    // Set the unhandled exception mode to force all Windows Forms errors to go through
    // our handler.
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    // Add the event handler for handling non-UI thread exceptions to the event. 
    AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    // Runs the application.
    Application.Run(new ErrorHandlerForm());
}
// Programs the button to throw an exception when clicked.
private void button1_Click(object sender, System.EventArgs e)
{
    throw new ArgumentException("The parameter was invalid");
}
// Start a new thread, separate from Windows Forms, that will throw an exception.
private void button2_Click(object sender, System.EventArgs e)
{
    ThreadStart newThreadStart = new ThreadStart(newThread_Execute);
    newThread = new Thread(newThreadStart);
    newThread.Start();
}
// The thread we start up to demonstrate non-UI exception handling. 
void newThread_Execute()
{
    throw new Exception("The method or operation is not implemented.");
}
// Handle the UI exceptions by showing a dialog box, and asking the user whether
// or not they wish to abort execution.
private static void Form1_UIThreadException(object sender, ThreadExceptionEventArgs t)
{
    DialogResult result = DialogResult.Cancel;
    try
    {
        result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception);
    }
    catch
    {
        try
        {
            MessageBox.Show("Fatal Windows Forms Error",
                "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
        }
        finally
        {
            Application.Exit();
        }
    }
    // Exits the program when the user clicks Abort.
    if (result == DialogResult.Abort)
        Application.Exit();
}
// Handle the UI exceptions by showing a dialog box, and asking the user whether
// or not they wish to abort execution.
// NOTE: This exception cannot be kept from terminating the application - it can only 
// log the event, and inform the user about it. 
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    try
    {
        Exception ex = (Exception)e.ExceptionObject;
        string errorMsg = "An application error occurred. Please contact the adminstrator " +
            "with the following information:\n\n";
        // Since we can't prevent the app from terminating, log this to the event log.
        if (!EventLog.SourceExists("ThreadException"))
        {
            EventLog.CreateEventSource("ThreadException", "Application");
        }
        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "ThreadException";
        myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
    }
    catch (Exception exc)
    {
        try
        {
            MessageBox.Show("Fatal Non-UI Error",
                "Fatal Non-UI Error. Could not write the error to the event log. Reason: "
                + exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
        finally
        {
            Application.Exit();
        }
    }
}
// Creates the error message and displays it.
private static DialogResult ShowThreadExceptionDialog(string title, Exception e)
{
    string errorMsg = "An application error occurred. Please contact the adminstrator " +
        "with the following information:\n\n";
    errorMsg = errorMsg + e.Message + "\n\nStack Trace:\n" + e.StackTrace;
    return MessageBox.Show(errorMsg, title, MessageBoxButtons.AbortRetryIgnore,
        MessageBoxIcon.Stop);
}



我已经经历了几次,没有任何运气.

我主要对使用UI ThreadException感兴趣.

我添加了:



I have worked through this a few times without any luck.

I am primarily interested in using the UI ThreadException.

I have added:

// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);



并创建了一个简单的Form1_UIThreadException处理程序.当我对此进行测试时,仍然没有捕获到由button1引发的异常.

我可以看到C#包括代码和处理程序,但是Exception机制似乎对我不起作用.

如果我只是在我的Application.Run(new Formi())上使用try/catch;在program.cs中,我可以捕捉到冒泡的异常.

我确实必须先注释掉ThreadException引用,否则将不起作用.因此它是有效的,但不会触发.

有没有人通过这个例子工作?你能提供我可能会想念的东西吗? :sigh:



And created a simple Form1_UIThreadException handler. When I test this the exception thrown by button1 is still not caught.

I can see that C# is including the code and the handler but the Exception mechanism does not seem to fire for me.

If I simply use a try/catch on my Application.Run(new Formi()); in program.cs I can catch the Exceptions that bubble up.

I do have to comment out the ThreadException references first or that does not work. So it is in effect but not firing.

Has anyone worked through this example? Can you offer what I may be missing? :sigh:

Thanks.

推荐答案

托利;

感谢您的回复.不确定我是否了解.

您是否将缩短的示例粘贴到VS 2010 Express上的Form项目中并运行它?
Hi Toli;

Thanks for your reply. Not sure I understand.

Did you paste the shortened example into a Form project on VS 2010 Express and run it?


会这样做.我对Msoft的示例感到有些沮丧,所以我应该想到这一点.谢谢.

我使用本地Visual Studio帮助,因此我的URL是127.0.0.1地址.主题是Application.ThreadException事件.如果将此输入到在线VS10 doc链接中,它将出现.

我正在尝试的代码归结为:

program.cs:
Will do. I am a bit frustrated with the Msoft example so I should have thought of that. Thanks.

I use the local Visual Studio Help so my URL is a 127.0.0.1 address. The topic is Application.ThreadException Event. If this was entered into the online VS10 doc link it would come up.

The code I am trying exactly boils down to:

program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Security.Permissions;

namespace WindowsFormsApplication1
{

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]

        static void Main()
        {
            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += new ThreadExceptionEventHandler(Form1_UIThreadException);

            // Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }

        }

        // Handle the UI exceptions by showing a dialog box, and asking the user whether
        // or not they wish to abort execution.
        public static void Form1_UIThreadException(object sender, ThreadExceptionEventArgs t)
        {
            MessageBox.Show(t.ToString());
        }
    }
}



Form1.cs:



Form1.cs:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            {
                InitializeComponent();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            throw new ArgumentException("The parameter was invalid");
        }
    }
}


这篇关于Application.ThreadException事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆