.NET 控制台应用程序中的全局异常处理程序

.NET Global exception handler in console application(.NET 控制台应用程序中的全局异常处理程序)
本文介绍了.NET 控制台应用程序中的全局异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

问题:我想在我的控制台应用程序中为未处理的异常定义一个全局异常处理程序.在asp.net中,可以在global.asax中定义一个,在windows应用程序/服务中,可以如下定义

Question: I want to define a global exception handler for unhandled exceptions in my console application. In asp.net, one can define one in global.asax, and in windows applications /services, one can define as below

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyExceptionHandler);

但是如何为控制台应用程序定义一个全局异常处理程序呢?
currentDomain 似乎不起作用(.NET 2.0)?

But how can I define a global exception handler for a console application ?
currentDomain seems not to work (.NET 2.0) ?


啊,愚蠢的错误.
在VB.NET中,需要在currentDomain前面加上AddHandler"关键字,否则在IntelliSense中看不到UnhandledException事件...
这是因为 VB.NET 和 C# 编译器对事件处理的处理方式不同.

Argh, stupid mistake.
In VB.NET, one needs to add the "AddHandler" keyword in front of currentDomain, or else one doesn't see the UnhandledException event in IntelliSense...
That's because the VB.NET and C# compilers treat event handling differently.

推荐答案

不,这是正确的做法.这完全按照它应该的方式工作,您也许可以从中工作:

No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:

using System;

class Program {
    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        throw new Exception("Kaboom");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

请记住,您无法以这种方式捕获由抖动生成的类型和文件加载异常.它们发生在您的 Main() 方法开始运行之前.捕捉这些需要延迟抖动,将有风险的代码移动到另一个方法中并对其应用 [MethodImpl(MethodImplOptions.NoInlining)] 属性.

Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.

这篇关于.NET 控制台应用程序中的全局异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
How to store delegates in a List(如何将代表存储在列表中)
How delegates work (in the background)?(代表如何工作(在后台)?)
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)