是否可以将Application.Run()方法放入catch中以避免应用程序终止?

Rik*_*ika 3 c# try-catch

我试图尽可能地保持(我的beta版本)应用程序运行,所以我在发生一些严重错误的情况下也放置了另一个try-catch内部Program.cs并且意外地关闭了应用程序.并且在catch我重写了Application.Run()方法以便应用程序可以在因任何原因被终止后自行恢复.
针对这种特定情况制定此类计划是否正确?
如果不对,那么为了保持程序运行,还有什么建议?

这是展示我的意思的示例代码:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Hossein;
using Pishro.Classes;

namespace Pishro
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmMain());
            }
            catch(Exception exc)
            {
                API.SaveAndShowLog(exc);
                Application.Run(new frmMain());
            }
        }
    }
  }
Run Code Online (Sandbox Code Playgroud)

usr*_*usr 6

全局处理异常是记录和警报的好主意.

像你这样的自动重启策略可能很有用.但是存在风险:如果崩溃已损坏全局数据结构,则重新启动应用程序可能会产生无法预测的结果,例如静默数据损坏.例如,文件可能仍处于打开状态并已锁定.锁可能尚未发布.静态变量可能处于未定义状态.流氓线程可能仍在运行,不知道应用程序UI被破坏.

我建议您通过启动应用程序的新流程重新启动应用程序.让旧过程死亡.