1

I'm trying to save some data when the program is forced to exit.

For example if the PC shuts down or it gets closed by the Task Manager.

It's not a console or a Winforms application. It's just a background process without a user interface.

namespace Test
{
    class Test
    {
        static void Main()
        {
            Application.ApplicationExit += new EventHandler(OnProcessExit);
            //some stuff to do here
        }

        static void OnProcessExit(object sender, EventArgs e)
        {
            //saving all the important data
            Console.WriteLine("Im out of here!");
            Environment.Exit(0);
        }
    }
}

This is what I tried. I didn't got any errors, but my handler isn't called.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136

2 Answers2

5

There are at least two issues here.

The Application.ApplicationExit event is raised only when you've called Application.Run() and the Run() method is about to return (e.g. you've called Application.Exit() or Application.ExitThread(), or closed the last/main window, etc.). In a non-GUI program where you've never called Application.Run(), the Application object doesn't have a chance to raise the event.

Forcefully terminating a process can prevent any more code from executing, including event handlers. For a non-GUI process, a more appropriate event to handle would be AppDomain.ProcessExit. But even this event might not be raised, if you terminate your process forcefully.

So, try the AppDomain.ProcessExit event. But be aware that depending on how the process is terminated, even that might not be raised.

If you need more specific help than that, provide a good Minimal, Complete, and Verifiable code example that shows what you've tried, reproduces whatever problem you're having, and explain in precise and specific details what exact behavior the code has now and what you want instead.


Additional reading:
How to run code before program exit?
C# Windows Program Exit Request (Detect Application.Exit) No Forms
How to detect when application terminates?

None of these related posts really seem to cover adequately the "forceful termination" scenario and so aren't technically exact duplicates of your question, but they do provide a variety of good discussion on techniques to detect your own process exiting.

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
0

If you or anyone of you who visits here are working on Form then this might help.

This is what worked for me:

public Form1{
  //some code...
  AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

}
public void OnProcessExit(object sender,EventArgs e){
   MyDataLoggerMethod("Monitoring ended.");
}