2

Can someone help me with alternative way for handling power events in .net core?

I am porting my .net framework window service applications to .net core 2.2, and in .net framework I was using ServiceBase class and itself methods for handling power events (OnPowerEvent). I want to handle events such as Suspend, Resume, etc.

Now I am using HostBuilder for hosting windows service and I couldn't find any solution for getting system power events.

Member2017
  • 431
  • 2
  • 8
  • 16
mata94
  • 43
  • 4

1 Answers1

0

You can use Worker Services. It has a StartAsync and StopAsync virtual method that you can override.

I advise you to upgrade to .NET Core 3.x because older versions won't be supported any more:

enter image description here

MatX
  • 108
  • 1
  • 6
  • Thank you for answer. I have already tried it, and for some reason that methods are only executed on stopping and starting service. I would like to handle system sleep and resume events. Currently on suspend, method StopAsync is not called, also on resume Start is not called. I have also added IApplicationLifetime service and register stop and start methods. I forgot to mention, host is created using WebHost. I would like to do some work when PC goes into sleep and to reactivate that state when PC is invoked. – mata94 Feb 27 '20 at 07:12
  • 1
    The way that Windows treats services is not the same as the way other OSs treat them. I don't think .NET Core provides OS level lifecycle events. So if I were you I would use Task Scheduler on Windows and rc files on UNIX so that when the PC boots up a command - your startup/resume command - is executed. – MatX Feb 27 '20 at 09:37
  • Yes, I understand. Thank you very much. – mata94 Feb 27 '20 at 09:47