問題描述
[我知道網上有 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).
這篇關于在任何未處理的異常的情況下退出應用程序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!