views:

282

answers:

2

I have been doing some extensive testing of a Windows Service I have been writing in C# .Net 3.5. I am having trouble getting Windows to give me enough time for my service to shutdown properly when I restart or shutdown the computer even though I am invoking the RequestAdditionalTime() method which should update the SCM and keep my service running. My code works properly if I manually stop the service however. I have primarily been testing this code in Windows Vista and Windows 7, upon deciding to test the code in Windows Xp everything worked perfectly. Does anyone know why this call does not work in Vista/7? I am thinking I need some kind of permission to keep the system from shutting down that I get by default in Xp but not in Vista/7.

+1  A: 

If the system isn't shutting down, your service can request additional time and your process will not get killed.

If the system is shutting down, your service has to shut down. You don't even get the normal 30 seconds that a service normally gets. Shutdown is more forceful than it used to be.

Windows programmer
Is there any way to know the amount of time your service will get to shutdown when you shutdown or restart the computer? I know the WaitToKillServiceTimeout is set to 12000 in W7 and 20000 in Vista, Xp. But even when you change this value in W7 or Vista it has little or no effect. Especially in Windows 7 it stomps your service within a few seconds. Thanks for the insight.
Kam Sheffield
I think there is no way to know. Suppose Windows allows 13 seconds for all services to shutdown. Some other service takes 12 seconds of cpu time (so other services can't execute during that time) and finally shuts down. That leaves 1 second for all the rest. Windows is going to kill them.
Windows programmer
A: 

In the non-shutdown case, RequestAdditionalTime() must be called more often than every 2 minutes:

    protected override void OnStop()
    {
        Thread.Sleep(60000);
        RequestAdditionalTime(180000);
        Thread.Sleep(60000);
        RequestAdditionalTime(180000);
        Thread.Sleep(5000);
    }

Note that despite the name, the time parameter is the total shutdown time requested.

Simon Buchan