Reputation: 133
As my question here: Stop program when thread finished?
I have a window service and an aspx page. In aspx page, I have to start the service. This service will run a thread, after thread finish, it will stop the service. After that, my aspx page have to show result to screen.
So, I have to: Check if service running - Start service - check if services stop - Print result to screen.
Currently, my code is like:
while(true){
if(isServiceStop){
MyService.Start();
while(true){
if(isServiceStop){
Print result;
break;
}
}
break;
}
}
This way, it will skyrocket my CPU_Usage, so, I want to know if there is any other way to achieve my request
Upvotes: 0
Views: 1411
Reputation: 133
I found that service have method WaitForStatus, so I only need to use below code and it work perfectly:
Myservice.WaitForStatus(ServiceControllerStatus.Stopped);
Upvotes: 0
Reputation: 133975
Create two EventWaitHandle objects to indicate the service's status:
private EventWaitHandle ServiceRunningEvent;
private EventWaitHandle ServiceStoppedEvent;
// in service startup
ServiceRunningEvent = new EventWaitHandle(False, EventResetMode.Manual, "RunningHandleName");
ServiceStoppedEvent = new EventWaitHandle(False, EventResetMode.Manual,
"ServiceStoppedEvent");
// Show service running
ServiceStoppedEvent.Reset();
ServiceRunningEvent.Set();
And when the service exits, have it flip the values:
ServiceRunningEvent.Reset();
ServiceStoppedEvent.Set();
In your ASP.NET application, you create the wait handles in the same way, but rather than setting their values, you wait on them. So:
// if service isn't running, start it and wait for it to signal that it's started.
if (!ServiceRunningEvent.WaitOne(0))
{
// Start the service
// and wait for it.
ServiceRunningEvent.WaitOne();
}
// now wait for the service to signal that it's stopped
ServiceStoppedEvent.WaitOne();
I do wonder, however, why you'd want to start and stop a service so often. Why not just have the service running all the time, and send signals when you need it to do things?
Upvotes: 1