c# - Windows 服务能否正常关闭需要数小时?

标签 c# .net windows-services shutdown long-running-processes

我们有一个 .NET Windows 服务,它以事务方式将大量高度关键的数据从 A 传送到 B。 我们还需要确保服务中使用的所有外部组件均未正确分配,并在关闭服务本身之前清理所有内容。 这可能需要几个小时!这是因为服务需要等待外部组件的回调,该回调会在 2、3 或 4 小时后到达。

  1. is it possible for Windows to wait so long for a service to shutdown gracefully?
  2. 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?
  3. also, as another scenario, what happens if the server needs to reboot? Can it wait hours for the service?
  4. 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/

相关文章:

c# - 带有 MongoDb 的 ASP.NET Core 3.1 中的身份服务器 4

c# - N 个连续字符的 .NET 正则表达式

c# - vs201 0 auto 化: Get the text value of a EnvDTE. CodeElement

windows-services - 安装 windows 服务错误 : cannot open service control manager on computer. 此操作可能需要其他权限

c# - Elasticsearch/Nest - 将 MatchPhrase 与 OnFieldsWithBoost 结合使用

c# - 闭包与类?

c# - Visual C# 中哪个库用于图形编程,Tao 还是 OpenTK?

c# - 字典的多态性

c# - 如何从 Windows 服务运行控制台应用程序?

c# - 使用Web API作为SignalR服务器并从Windows服务使用它