Cannot receive callback after calling RegisterServiceCtrlHandlerEx() in Microsoft.Extensions.Hosting.BackgroundService

guliteb 36 Reputation points
2022-07-04T10:34:57.953+00:00

I followed links to implement a Windows service in .NET and ASP NET.

https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio

Now I want to handle Power events and follow the link to call RegisterServiceCtrlHandlerEx() in my BackgroundService construct method.
https://learn.microsoft.com/en-us/windows/win32/power/registering-for-power-events

The call to RegisterServiceCtrlHandlerEx succeeds, but there is no any callback when I change some Power settings.

Any idea why it is not working?

Thanks.

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,125 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,686 Reputation points
    2022-07-04T16:24:09.673+00:00

    you used the cross platform template and it does not support service events. You need to create a new console project (there is no template) and use ServiceBase to create the service callback.

    https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase?view=dotnet-plat-ext-6.0

    Example

    https://dotnetcoretutorials.com/2019/09/19/creating-windows-services-in-net-core-part-1-the-microsoft-way/

    Typically when creating a service, you run the actual service code on a separate thread, you can also write as async. For example the onStop callback needs to be able to stop the service processing code, you can use a cancellation token for this.

    Depending on you needs, you may also need to implement a ServiceProcessInstaller

    https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.serviceprocessinstaller?view=netframework-4.8&viewFallbackFrom=dotnet-plat-ext-6.0

    Note: I’ve only written services in C/C++, but the above libraries look like thin wrappers around the o/s code.