问题
I'm having an issue that I can't figure out regarding a Windows Service I have written in C#. What I am trying to do is wait for a specified period for a child process to terminate before I am forced to kill it and stop the service. I have set my timeout for anywhere from 5 to 15 seconds and my service waits the appropriate amount of time and then kills the child and stops when I stop it via the mmc service window. However if I shutdown the computer my service gets blown away before it is able to wait and stop properly. I have read that Windows allows for a timeout of 30 seconds for a service to shutdown before it blows it away. My code is executing in much less time than 30 seconds, max is around 20 seconds or so, depending on what I set the timeout at.
I have tried using the SetServiceStatus() function in the win32 Api but it has not changed the function of the code. I have verified that the function call is succeeding. Is there any other way to force Windows to wait for my service to shutdown properly? I am testing it in Windows 7 x86, and Windows Vista Sp1 x86.
回答1:
Windows will not let any service prevent shutdown, this is by-design. as Gyuri says, you have to consider a different design for your app.
回答2:
This is a global Windows setting, apparently: http://support.microsoft.com/kb/305788. I would be worried if I had to rely on the users to let my service shut down. I would save my data periodically instead.
回答3:
OnSTart and OnSTop are inherited from a base class which does quite a bit for you. All your implementations of these methods should do is start or stop your client code, windows will do the rest.
I'll caveat this with the fact that I use C# and .Net's implementation of ServiceBase does this, I cannot talk authoritatively about C/C++ code or APIs.
来源:https://stackoverflow.com/questions/2008807/forcing-windows-to-wait-for-a-service-to-stop-when-it-is-shutting-down