Im currently developing a program in C#, that monitors the status of services, running on a server. I'm using System.ServiceProcess.ServiceController's waitforstatus funktion. The Problem is, if I run my program as an Consol-Program, everything works fine and the program detects status changes nearly in realtime. But if I run it as a Windows Service, it works very unreliable and delayed. Anyone an idea how to fix this?
Here the code (it runs in a seperated thread):
while (true)
{
lock (_myService)
{
_myService.Refresh();
if (_myState == ServiceState.running)
_myService.WaitForStatus(ServiceControllerStatus.Stopped);
else if (_myState == ServiceState.stopped)
_myService.WaitForStatus(ServiceControllerStatus.Running);
if (_myService.Status == ServiceControllerStatus.Running)
_myState = ServiceState.running;
if (_myService.Status == ServiceControllerStatus.Stopped)
_myState = ServiceState.stopped;
stateChanged?.Invoke(this, new ServiceStateChangeEventArgs(_name, _myState));
}
}