Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to stop a Windows Service gracefully?

Status
Not open for further replies.

EwS

Programmer
Dec 30, 2002
398
0
0
US
I have a Windows Service which processes some files every X seconds. The service should run 24/7 unless there is an exception, in which case I stop the service. However, there are times when I would want to stop the service manually (through Admin Tools/Services). How do I ensure that when I do that while the function that does the file processing is still executing, the service will wait for the function to finish? Is there anything I can put in OnStop() to detect whether the function is running or not? I suppose I could have the function turn some app settings on when it starts executing and off when it finishes executing, and add some code in OnStop() to check the setting. However, I would have to implement a loop to constantly check for the flag, plus I don't know how long OnStop() can wait?

I would appreciate any suggestions. Thank you.
 
In my OnStop() event, I do this:
Code:
// Block the thread until the thread terminates 
// or the specified time elapses.
while (!fpThread.Join(500)) // 500 ms
{
   // Request additional time to stop the service
   // to prevent the Service Control Manager from 
   // marking the service as not responding.
   this.RequestAdditionalTime(1000); // 1 second
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top