0

I have a BackgroundService that needs to perform an operation before the OS shuts down. Is there any way to do this with an IHostedService since there isn't an OnShutdown() event like in ServiceBase?

I tried making it work by implementing StopAsync, but it started to add a lot of complexity to the project since that runs any time the service is stopped.

1 Answers1

1

You can implement StopAsync and check for windows shutdown using Win32 API (link).

const int SM_SHUTTINGDOWN = 0x2000
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int GetSystemMetrics(int nIndex);

public override System.Threading.Tasks.Task StopAsync(System.Threading.CancellationToken cancellationToken)
{
    bool isShuttingDown = GetSystemMetrics(SM_SHUTTINGDOWN) != 0;
    if (isShuttingDown)
    {
        //Do your thing here
    }
}
John Wu
  • 50,556
  • 8
  • 44
  • 80