退出 .NET 应用程序的通用方法
我知道有几种退出应用程序的方法,例如 Application.Exit()、Application.ExitThread()、Environment.Exit() 等。
我有一个外部“commons”库,我正在尝试创建一个通用的 FailIf 方法,将失败记录到日志中,执行此操作、执行此操作、执行此操作,然后最终退出应用程序...这是它的简短版本。
public static void FailIf(Boolean fail, String message, Int32 exitCode = 1)
{
if (String.IsNullOrEmpty(message))
throw new ArgumentNullException("message");
if (fail)
{
//Do whatever I need to do
//Currently Environment.Exit(exitCode)
Environment.Exit(exitCode);
}
}
我读到,对于 WinForm 应用程序来说,使用 Environment.Exit 并不是处理问题的最佳方式,而且在使用 WPF 应用程序和 Silverlight 时,有不同的退出方式...我的问题实际上是:
我该怎么办优雅地退出以覆盖所有应用程序类型?
I understand that there are a few ways to exit an application, such as Application.Exit(), Application.ExitThread(), Environment.Exit(), etc.
I have an external "commons" library, and I'm trying to create a generic FailIf method that logs the failure to the logs, does this and that and this and that, then finally exits the application... here's a short version of it.
public static void FailIf(Boolean fail, String message, Int32 exitCode = 1)
{
if (String.IsNullOrEmpty(message))
throw new ArgumentNullException("message");
if (fail)
{
//Do whatever I need to do
//Currently Environment.Exit(exitCode)
Environment.Exit(exitCode);
}
}
I have read that using Environment.Exit isn't the best way to handle things when it comes to WinForm apps, and also when working with WPF apps and Silverlight there are different ways to exit... My question is really:
What do I put to exit gracefully to cover all application types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
阅读有关使用环境和应用程序之间的区别的文章:
Application.Exit Vs Environment.Exit
该页面底部有一个您想要执行的操作的示例:
Read this about the difference between using Environment and Application :
Application.Exit Vs Environment.Exit
There's an example of what you want to do in the bottom of that page:
如果只是中止,请使用
Environment.Exit()
。如果这是非常关键的事情(无法处理任何类型的清理),请使用Environment.FailFast()。If it's just an abort, use
Environment.Exit()
. If it's something very critical (that can't handle any sort of cleanup), useEnvironment.FailFast()
.我建议使用基本的异常处理,因此不要抛出 System.Environment.Exit(1) 抛出 new ApplicationException(message) ,它将异常冒泡到 main 方法,在您的情况下是这样的:
只需确保从以下位置抛出异常 :主线程,否则当然在抛出之前调用它
I would recommend using basic exception handling, so instead of System.Environment.Exit(1) throw new ApplicationException(message) which bubbles up the exception to the main method, in your case something like this:
Just make sure you throw the exception from the main thread, else invoke on it before throwing ofcourse