Capture shutdown command for graceful close in .NET Core
The AppDomain.CurrentDomain.ProcessExit
event is now available in .NET Core 2.0, and I can confirm that it works fine on Linux. Before .NET Core 2.0, AssemblyLoadContext.Default.Unloading
is probably a working alternative.
If you can update to dotnet core 2.1 (or later) you should consider using the IHost
interface for console apps and IHostedService
for asp.net core apps (2.0 and upwards) which are designed for just this sort of thing - telling the framework you have background processes that need to be notified on shutdown.
Admittedly you may need AppDomain.CurrentDomain.ProcessExit
as well for the killed process scenario, but using IHost/IHostedService will give you more time for a graceful shutdown in most application shutdowns.