If we're just talking about Windows, I can use the Microsoft.Win32.SystemEvents.SessionEnding
Is there something cross-platform that I can use? I want something that works with Windows and Linux. I shall be using .NET 6.0
If we're just talking about Windows, I can use the Microsoft.Win32.SystemEvents.SessionEnding
Is there something cross-platform that I can use? I want something that works with Windows and Linux. I shall be using .NET 6.0
To my knowledge, there is no straightforward and reliable way to determine this in a Linux environment, let alone a cross-platform solution. You will need to implement a linux-specific way to detect this.
As @fredrik mentioned in the comments, using PosixSignal
would let you know that your application is being asked to terminate, but not why. You can nevertheless examine the situation upon receiving a SIGTERM
to determine if the system is indeed shutting down. For example, running systemctl is-system-running
would return "stopping" if that is the case.
If we assume a modern Linux desktop environment, a more robust alternative could be to subscribe to the D-bus signal PrepareForShutdown
. From the systemd documentation:
The PrepareForShutdown() and PrepareForSleep() signals are emitted when a system suspend or shutdown has been requested and is about to be executed, as well as after the the suspend/shutdown was completed (or failed)...
The library Tmds.Dbus provides an async API to listen to that signal in your .net app. You will still need to deal with the fact that you'll receive this AND the SIGTERM
in sequence.