C# Windows 服务的全局异常处理程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1682128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:58:34  来源:igfitidea点击:

Global exception handler for windows services?

c#.netexceptionwindows-services

提问by Jeremy Odle

Is there a way to globally handle exceptions for a Windows Service? Something similar to the following in Windows Forms applications:

有没有办法全局处理 Windows 服务的异常?Windows 窗体应用程序中类似于以下内容:

Application.ThreadException += new ThreadExceptionEventHandler(new ThreadExceptionHandler().ApplicationThreadException);

采纳答案by Plip

Here is some pretty robust code we advise people to use when they're implementing http://exceptioneer.comin their Windows Applications.

下面是一些非常健壮的代码,我们建议人们在他们的 Windows 应用程序中实现http://exceptioneer.com时使用。

namespace YourNamespace
{
    static class Program
    {

        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException((Exception)e.ExceptionObject);
        }

        static void HandleException(Exception e)
        {
            //Handle your Exception here
        }

    }
}

Thanks,

谢谢,

Phil.

菲尔。

回答by JaredPar

Have you tried

你有没有尝试过

AppDomain.CurrentDomain.UnhandledException

This will fire for unhandled exceptions in the given domain no matter what thread they occur on. If your windows service uses multiple AppDomains you'll need to use this value for every domain but most don't.

这将针对给定域中未处理的异常而触发,无论它们发生在哪个线程上。如果您的 Windows 服务使用多个 AppDomain,则您需要为每个域使用此值,但大多数不需要。