有没有办法全局处理Windows服务的异常?类似于Windows窗体应用程序中的以下内容:
Application.ThreadException += new ThreadExceptionEventHandler(new ThreadExceptionHandler().ApplicationThreadException);
答案 0 :(得分:25)
你试过吗
AppDomain.CurrentDomain.UnhandledException
这将触发给定域中的未处理异常,无论它们出现在哪个线程上。如果您的Windows服务使用多个AppDomain,则您需要为每个域使用此值,但大多数不需要。
答案 1 :(得分:21)
以下是一些非常强大的代码,我们建议人们在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
}
}
}
谢谢,
菲尔。