简体   繁体   中英

C# windows service does not always stop on shutdown

I created a windows service with c# 2010. The problem is that when computer shuts down the service does not have time to stop and onstop is not always executing. I say not always because sometime it manages to stop. I have tried to use windows pre-shutdown notification that was introduced at vista, however the results are better but not absolute.

Is there anyway to get windows wait for my service to stop? Is there anyway to change the order windows stops the services?

According to http://msdn.microsoft.com/en-us/library/windows/desktop/ms685149(v=vs.85).aspx , a service normally has about 20 seconds to shut down before the system gives up and shuts down anyway.

You might be able to send STOP_PENDING messages back if your service needs more time to shut down, but even then you're limited to about 125 seconds before the system figures you're never going to shut down, and pulls the rug out from under you.

In C#, you would have your service call RequestAdditionalTime during shutdown. Again, there's no guarantee that you'll get that extra time, but you can ask for it. Remember, though, if you ask for more time you better be done before that time expires, or you can ask for more. But eventually the system will shut you down (again, probably in less than 2 minutes).

In general, I've found that it's best if you construct your service so that you can shut it down quickly. If you can't shut down in a few seconds, you probably need to change your design.

This can be answer for you (and for somebody, who search same answer): Why doesn't the RequestAdditionalTime() method work on restart in Vista/7? :

... 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.

This is the reason, why it sometimes shutdown correctly a sometimes doesn't.

By the way, Vista has 20 sec. to kill services, W7 has 12 sec. and W8 has 5 sec.

在从ServiceBase派生的服务类中,可以替代OnStop来请求其他时间:

base.RequestAdditionalTime(1000 * 60 * 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM