• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 831
  • Last Modified:

How to stop a Windows Service gracefully?

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.
0
EwS
Asked:
EwS
  • 2
2 Solutions
 
Jason EvansSenior Software DeveloperCommented:
Hi there.

Here's a link to a similar issue:

http://www.thescripts.com/forum/thread124604.html

What you can do is use the thread.Join technique to try and come to a smooth halt.

Hope this help.s
Jas.
0
 
slado2Commented:
If your service takes some time to stop you should inform servicemanager that the service status is stop pending and you need some more time.
http://msdn2.microsoft.com/en-us/library/d56de412(VS.80).aspx
0
 
slado2Commented:
To make things clear:
I assume that your service processing (file operations in your case) is done in a separate thread. When OnStop is called then you should call Join(int Time)
http://msdn2.microsoft.com/en-us/library/6b1kkss0.aspx
The call RequestAdditionalTime to inform the service manager that your service is still stopping if the thread is not finished yet.
http://msdn2.microsoft.com/en-us/library/system.serviceprocess.servicebase.requestadditionaltime.aspx
protected override void OnStop()
{
  int joinTimeout = 500; // 500 ms
  while(!FileProcessingThread.Join(joinTimeout))
  {
    this.RequestAdditionalTime(1000);  // request additional 1 second to stop the service
  }
}

Open in new window

0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now