简体   繁体   English

Windows Forms 未处理的异常崩溃

[英]Windows Forms Unhandled Exception Crash

I have code that caters for my winforms application to handle an an unhandled exception.我有适合我的 winforms 应用程序的代码来处理未处理的异常。 My application however still crash.然而,我的应用程序仍然崩溃。

I do, at this stage, have no understanding why this behavior is.在这个阶段,我确实不明白为什么会出现这种行为。 I would appreciate your assistance.我会很感激你的帮助。

Here is my code:这是我的代码:

 [STAThread]
    private static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        bool result;
        var mutex = new System.Threading.Mutex(true, "MyApplication", out result);
        if (!result)
        {
            MessageBox.Show("Another instance is already running.");
            return;
        }
        Application.ThreadException += ApplicationThreadException;
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
        Memory.frmMain = new MainForm();
        Application.Run(new MyApplicationContext());
        GC.KeepAlive(mutex);
    }
    public static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        MessageBox.Show(((Exception)e.ExceptionObject).Message);
        ((Exception)e.ExceptionObject).AddLog();
        Memory.processtranslations.IsProcessing.Enabled = true;
    }
    public static void ApplicationThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.Message);
        e.Exception.AddLog();
        Memory.processtranslations.IsProcessing.Enabled = true;
    }

Try to add [HandleProcessCorruptedStateExceptions] attribute to your Main method.尝试将[HandleProcessCorruptedStateExceptions]属性添加到您的 Main 方法中。 What's more, get your main loop into try..catch:更重要的是,让你的主循环进入 try..catch:

[HandleProcessCorruptedStateExceptions]
static void Main(string[] args)
{
 //other code
  
  try
  {
    Application.Run(new MyApplicationContext());
  }catch(Exception)
  {
    //...
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM