在任何未处理的异常的情况下退出应用程序 [英] Exit the application in case of any unhandled exception

查看:27
本文介绍了在任何未处理的异常的情况下退出应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[我知道网上有 100 多个类似的问题,但我仍然无法找到解决此问题的有效解决方案,因此将其发布.]

我有一个 c# Win-Form 应用程序.该应用程序用于通过 FTP 从另一台服务器下载图像.

I have a c# Win-Form application. The application is used for downloading images via FTP from another server.

在任务调度程序的帮助下,应用程序每天运行 3 次并下载图像,然后自动关闭.

With the help of a task scheduler, the application runs 3 times a day and downloads the images and after that it closes automatically.

去年它运行良好,但是,自今年年初以来,我们收到了来自应用程序的请求超时"或操作超时"等未处理的异常.

It used to work fine last year, however, since the beginning of this year, we are getting unhandled exception like "request timed out" or "operation timed out" from the application.

因此,应用程序不会自动关闭,而是显示一个带有继续"和退出"按钮的窗口对话框.

Thus instead of the application getting closed automatically, it shows a windows dialog with "continue" and "quit" button.

我的要求是应用程序应该自动关闭,以防引发任何未处理的异常.

My requirement is that the application should close automatically in case any unhandled exception is thrown.

我在我的 program.cs 中编写了以下代码来处理这个问题.但是,这也不起作用,我仍然收到异常窗口.

I have written the following code in my program.cs to handle this. However, this is also not working and I am still getting exceptions window.

    [STAThread]
    static void Main()
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;
        currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
    static void MyHandler(object sender, UnhandledExceptionEventArgs args)
    {
        System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
        System.Windows.Forms.Application.Exit();
        System.Environment.Exit(0);
        proc.Kill();
        return;
    }

推荐答案

您可能需要订阅几个事件以确保捕获所有可能的异常:

There are several events to which you may need to subscribe to ensure that you catch EVERY possible exception:

Application.ThreadException += yourThreadExceptionHandler;
AppDomain.CurrentDomain.UnhandledException += yourUnhandledExceptionHandler;
TaskScheduler.UnobservedTaskException += yourUnobservedTaskExceptionHandler;

当然,您还应该在程序主体周围有一个 try/catch:

And of course you should also have a try/catch around the body of the program:

public static void Main()
{
    try
    {
        runProgram();
    }

    catch (Exception exception)
    {
        // Your main exception handler.
    }
}

您可以使用所有附加的处理程序调用的通用异常处理机制,以避免重复代码.UnobservedTaskException 可能是您想要以不同方式处理的事情(记录它,否则可能会忽略).

You can have a common exception handling mechanism that all your attached handlers call, to avoid duplicated code. UnobservedTaskException might be something you want to handle differently (log it and otherwise ignore, perhaps).

这篇关于在任何未处理的异常的情况下退出应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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