I have a small console app that runs continuously on an Azure Windows 10 VM, doing some calculations.
But I would like it 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?