我们有一个 .NET Windows 服务,它以事务方式将大量高度关键的数据从 A 传送到 B。 我们还需要确保服务中使用的所有外部组件均未正确分配,并在关闭服务本身之前清理所有内容。 这可能需要几个小时!这是因为服务需要等待外部组件的回调,该回调会在 2、3 或 4 小时后到达。
- is it possible for Windows to wait so long for a service to shutdown gracefully?
- are there options in a service where I can dictate what happens when the service is being shutdown by the operating system, e.g. prevent the shutdown altogether?
- also, as another scenario, what happens if the server needs to reboot? Can it wait hours for the service?
- Is there a limit on how long the OS will wait on the service before killing it?
最佳答案
您可以使用 CanStop, CanShutdown, CanHandlePowerEvent在计算机关闭时收到通知并做出充分响应。
使用 ServiceBase.RequestAdditionalTime 方法请求额外的时间来终止您的线程:
protected override void OnShutdown()
{
base.RequestAdditionalTime(MaxTimeout);
serviceCore.OnShutdown();
Stop();
}
如果您的 OnShutdown() 阻塞时间超过 20 秒(默认值存储在注册表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\WaitToKillServiceTimeout 中),您的服务将被标记为无响应并被终止。
There is a good blog post from the BCL team on that subject that I recommend.
关于c# - Windows 服务能否正常关闭需要数小时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7441061/