避免“程序停止工作"在 C#/.NET 中 [英] Avoid "program stopped working" in C#/.NET

查看:25
本文介绍了避免“程序停止工作"在 C#/.NET 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 C#/.NET 编写的控制台应用程序,我想从脚本 (nant) 运行它.如果控制台应用程序中出现异常,我希望 nant 继续,但在 Windows Vista 中会弹出一个搜索解决方案并要求调试等的弹出窗口.

I have a console application written in C#/.NET that I want to run from a script (nant). If an exception occurs in the console application, I would like nant to continue, but in Windows Vista there is a popup that searches for solutions and asks for debug etc.

我想避免在控制台应用程序中发生异常时弹出程序停止工作".如何从 C#/.NET 控制它?

I would like to avoid the popup with "program stopped working" when an exception happens in the console application. How can I control this from C#/.NET?

(类似的问题解决了C 语言的问题,但我想要 C#/.NET 的解决方案.)

(A similar question addresses the issue for the C language, but I would like a solution for C#/.NET.)

(澄清一下:我希望将异常传递给 nant,但 没有弹出窗口.)

(To clarify: I would like the exception to be passed to nant, but without the popup.)

推荐答案

出现未处理的异常时会弹出 JIT 调试器.也就是说,异常会沿着堆栈一路向上到达运行时中任何线程的根.

The JIT debugger popup occurs when there's an unhandled exception. That is, an exception tunnels all the way up the stack to the root of any thread in the runtime.

为避免这种情况,您可以处理 AppDomain.CurrentDomain.UnhandledException 事件,只需调用 Environment.Exit(1) 优雅退出.

To avoid this, you can handle the AppDomain.CurrentDomain.UnhandledException event and just call Environment.Exit(1) to exit gracefully.

这将处理 AppDomain 中所有线程上的所有异常.除非你做任何特别的事情,你的应用可能只有一个 AppDomain,所以把它放在你的 public static void Main 方法中就足够了:

This will handle all exceptions on all threads within your AppDomain. Unless you're doing anything special, your app probably only has one AppDomain, so putting this in your public static void Main method should suffice:

AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
    Console.Error.WriteLine("Unhandled exception: " + args.ExceptionObject);
    Environment.Exit(1);
};

在这种情况下,您可能也应该使用 NAnt 记录器来写出错误(不过暂时不记得 API.)

You should probably use the NAnt logger to write out the error in this case too (can't recall the API for this offhand though.)

您还可以禁用 JIT 调试在机器上.我只会在某些情况下推荐这个,例如专用的构建服务器.

You can also disable JIT debugging on the machine. I would only recommend this in certain circumstances such as for a dedicated build server.

这篇关于避免“程序停止工作"在 C#/.NET 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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