如果出现任何未处理的异常,请退出应用程序 [英] Exit the application in case of any unhandled exception

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

问题描述

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

我有ac#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.

因此,不是自动关闭应用程序,而是显示带有继续和退出按钮的Windows对话框。

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;

当然,您还应该在程序主体周围进行尝试/捕获:

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