Home > Net >  .NET Console App - can it detect its own imminent termination due to system shutdown?
.NET Console App - can it detect its own imminent termination due to system shutdown?

Time:01-25

I have a small console app that runs continuously on an Azure Windows 10 VM, doing some calculations.

But what I would like would be if the job could detect when the VM is about to reboot, or when it itself is about to terminate, and write something to ApplicationInsights.

Can a .NET console app, running under Windows 10, detect its own termination (due to a system shut down, or for other reasons) in time to write some telemetry?

I've set up the following events (an example of one handler is shown), but they never seem to produce any telemetry, which makes me think there's something I don't "get" about how a shutdown happens. Perhaps there isn't time for the telemetry to be sent.

   AppDomain.CurrentDomain.UnhandledException  = CurrentDomain_UnhandledException;
   AppDomain.CurrentDomain.ProcessExit  = CurrentDomain_ProcessExit;
   Process.GetCurrentProcess().Exited  = Program_Exited;
}

private static void Program_Exited(object? sender, EventArgs e)
{
   telemetryClient?.TrackEvent("ProgramEnding");
}
   

I searched, of course. I found a reference for the Microsoft.Win32.SystemEvents class, which has events for SessionEnding, although it looks as if I'd need to generate a hidden form in order to be notified of that event (ugh).

Is that the direction I need to head in? And, is it even possible for a console app to detect its own termination in time to respond?

CodePudding user response:

I found a reference for the Microsoft.Win32.SystemEvents class, which has events for SessionEnding, although it looks as if I'd need to generate a hidden form in order to be notified of that event

More specifically, you need a message pump to receive the WM_ENDSESSION message from the OS. You can do that as you wish, whether by using a hidden form with the managed API or by manually calling GetMessage/DispatchMessage on a window you create manually with native API.

is it even possible for a console app to detect its own termination in time to respond?

The way shut down works is that you get the above message, and while you're processing it (either directly or through the SessionEnding event handler) the system will wait for you and eventually show that "programs still need to close" message, and the user can choose to allow more time or not. Unless it's a critical shutdown in which case you only get a short time window.

So yes, you should have plenty of time to do any sane shut down, even including registering for a restart of your application when Windows boots up again.

  • Related