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

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

问题描述

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



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



(类似的问题地址 C语言的问题,但我想要一个解决方案为C#/。NET。)



(要澄清:我想将异常传递给nant,但是没有弹出窗口。)

解决方案

当有一个未处理的异常时,会发生JIT调试器弹出窗口。也就是说,一个异常通过堆栈的方式遍历运行时任何线程的根目录。



为了避免这种情况,您可以处理 AppDomain.CurrentDomain.UnhandledException 事件,只需致电 环境.Exit(1) 可以正常退出。



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

  AppDomain.CurrentDomain.UnhandledException + =(sender,args)=> 
{
Console.Error.WriteLine(未处理的异常:+ args.ExceptionObject);
Environment.Exit(1);
}

您应该可以使用NAnt记录器在这种情况下写出错误(不能记得这个API的API。)



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


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.

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?

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

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

解决方案

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.

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

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);
}

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.)

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天全站免登陆