I have this service registered and starting up when the PC is turned on. The service is just monitoring a folder activity and it should write to a text file some data when the PC is being shutdown.
I am trying to do this when the StopAsync
function gets fired, which is part of the BackgroundService implementation.
To simplify testing, I have just added a logging message that should appear in the windows events log next time I restart the PC. If I stop the service manually, this message appears correctly, and even when implementing the saving file task, that happens too.
But when I turn off the PC, once I start it again, all other messages are in the Windows Event log except the last one, the one from StopAsync
.
My StopAsync
function looks like this:
public override Task StopAsync(CancellationToken cancellationToken) {
logger.LogWarning("Test Service is Stopping...");
return base.StopAsync(cancellationToken);
}
I dont have the "Fast Startup" system configuration set.
Am I missing something?
After looking into this issue for a long time, and finally having contact with the developers of .NET, turns out that in the case of a shutdown, the task StopAsync
will fire but you cant be 100% sure that all the resources you need are still loaded. This includes the logging systems.
For more detailed information here is the link with the issue.
This is relevant up to .NET Core 7.