Ray Yago
Ray Yago

Reputation: 145

Get a notification when Windows Service state change?

im trying to figure out how i can get a notification when the state of a Windows Service changes. First i tryied a timer that check the state every view seconds with the ServiceControl.State. I found this "NotifyServiceStatusChange" but no examples or something like that and dont know how to use that.

Or is there a other way?

Background information: I have an application. The application has 2 buttons. Everytime the state of the service changes one of the buttons should be disabled. Like Service-State running then disable the "Start Service" button.

Upvotes: 1

Views: 2719

Answers (2)

clamchoda
clamchoda

Reputation: 4951

Have you had a look at the ServiceController Class? Something like this should get you started.

ServiceController sc = new ServiceController("ServiceName");
switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        break;
    case ServiceControllerStatus.Stopped:
        break;
    case ServiceControllerStatus.Paused:
        break;
}

If you would like to avoid constantly polling on a timer, you could have a look at WaitForStatus. Have your background workers always waiting for a specified status to enable buttons, disable buttons or whatever.

This is a very basic example, but to answer your question about infinite loop - no. see my comments and debug step this, you will understand why.

ServiceController sc = new ServiceController("ServiceName");
for (;;)
{
     // for pauses execution, waiting for stopped status.
     sc.WaitForStatus(ServiceControllerStatus.Stopped);
     // continues when stopped status signaled, disable button 

     // for waiting for running status.
     sc.WaitForStatus(ServiceControllerStatus.Running);
     //continues when running status signaled, enable button
     // for will continue but wait for stopped status signal

}

This is why I recommended doing this check in a background worker or just something off of the main thread so that your entire application does not get jammed up while waiting for status changes.

Upvotes: 1

Anderson Luiz Ferrari
Anderson Luiz Ferrari

Reputation: 341

If I understood it correctly, you have a windows service running in the background and another app that wants to be notified. If that is the case, you will need to implement some form of communication between them. Depending on your requirements, and where you are going to run the solution, you can use Message Queue (MSMQ for example) where you can subscribe/broadcast your messages. Another alternative it would be to user some Real Time Communication (like TCP/Socket, signalR or even using firebase to notify your app).

Upvotes: 0

Related Questions