处理多线程应用程序中的静态构造函数异常

时间:2009-09-21 18:25:13

标签: c# exception static

我有一个静态类,在其构造函数中创建了几个工作线程。如果在创建工作程序之前发生异常,我的Application.ThreadException处理程序(用于在未知可恢复的错误发生时关闭应用程序)会正常触发,一切正常。一旦创建了第一个工作线程,但除了处理程序触发之外,我得到一个“MYAPP遇到问题并需要关闭。我们很抱歉给您带来不便。” MS错误报告对话框。

在这个特定的实例中,我可以重新排序代码以最后创建线程(在任何可能触发异常的资源初始化/访问问题之后),但这只不过是问题的一个绑定,并没有给我任何有关实际情况的信息。

希望我已经从我的应用程序中删除了足够的代码来展示我在这里要做的事情。

class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        try
        {
            Application.Run(theForm);
            theForm.Dispose();

        }
        catch (Exception e)
        {
            //doing this to use the same handler here and for Application.ThreadException
            ThreadExceptionEventArgs argsEx = new ThreadExceptionEventArgs(e);
            FatalExceptionHandler(null, argsEx);

        }
        finally
        {
            MyStaticClass.KillThreads();
        }
    }

    public static void FatalExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs ex)
    {
        Exception e = ex.Exception;
        try
        {
            //lots of stuff to give more useful error messages for known problems
            //and display them in a messagebox.
        }
        // if anything went wrong scraping the exception text for formatting, show the raw value.
        catch
        {
            MessageBox.Show(e.Message);
            return;
        }
        // after showing the MessageBox, close out the app.
        finally
        {
            System.Environment.Exit(1);
        }
    }
}

class MyStaticClass
{
    static MyStaticClass()
    {
        myThread = new Thread(new ThreadStart(SomeMethod));

        //if this exception is thrown everything works normally
        //Throw new Exception("KABOOM");

        myThread.Start();

        //if this exception is thrown a windows error reporting dialog appears 
        //along with the messagebox from program.FatalExcetion handlder             
        //Throw new Exception("KABOOM");
    }


    public void KillThreads()
    {
        //clean up the worker threads
    }
}

2 个答案:

答案 0 :(得分:4)

在应用程序启动期间,不会在特定时间调用静态构造函数。特别是,如果您从未从另一个类引用MyStaticClass,则可能永远不会初始化它。由于您无法以任何理智的方式对此进行推理,因此您应该为静态构造函数中具有非平凡代码的类型提供StaticInitialize()方法(或类似方法)以及静态初始化代码确实需要运行的情况。将代码从静态构造函数移动到静态初始化方法。

答案 1 :(得分:1)

仅为UI线程未处理的异常引发Application.ThreadException(因为它是Application类的一部分)。工作线程未处理的异常事件是AppDomain.UnhandledException。当工作线程发生未处理的异常时,将引发此事件,然后显示系统崩溃对话框。 AppDomain.UnhandledException仅用于记录目的,并且没有记录的方法可以防止显示系统崩溃错误对话框。