How to handle application crash in code and do cleanup/ save state

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
 
            if (ex != null)
            {
                //Log error
            }
 
            if (e.IsTerminating)
            {
                Console.WriteLine("The app is terminating because of an unhandled exception.");
            }
 
            CleanupTasks();
        }

Another thing - IsBackgroundThread is actually useful to just let the OS know that this thread will not keep the process alive. I.e., the process in windows terminates when the last non-background thread exits.

So, if you have a non-background thread and it is running your process will remain running.

Did you know that unlike native code, in .NET the finally area is executed even if the application crashes? - this only happens for managed code.

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

Enable Visual Studio to use more than 2GB of memory