简体   繁体   中英

Windows Forms Unhandled Exception Crash

I have code that caters for my winforms application to handle an an unhandled exception. 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. What's more, get your main loop into try..catch:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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