如何在停止topshelf托管的Windows服务之前添加超时

时间:2016-08-15 15:12:44

标签: windows-services topshelf

我使用Top-Shelf安装了许多Windows服务。

我想知道在停止服务时是否有办法设置超时,以启用服务当前处理的正在进行的进程,以便在服务实际关闭之前完成? 我想在终止Top-Shelf之前等待X秒。

这是我作为服务安装的控制台:

    static int Main(string[] args)
    {
        return (int)HostFactory.Run(x =>
        {
            string serviceName = new ServiceNameResolverImpl().GetServiceName();
            x.SetServiceName(serviceName);
            x.SetDisplayName(serviceName);
            x.SetDescription(serviceName);

            x.UseAssemblyInfoForServiceInfo();
            x.RunAsLocalSystem();
            x.StartAutomaticallyDelayed();
            x.SetStartTimeout(TimeSpan.FromMinutes(1));
            x.Service<ServiceImpl>();
        });
    }

谢谢!

2 个答案:

答案 0 :(得分:1)

在您的服务实现中,使用HostControl来请求额外的关机时间(我假设您的服务已经实现了ServiceControl,因为这是.Service<T>期望的那样 - 请注意服务控制管理器可能会也可能不会批准请求:

public class ServiceImpl : ServiceControl
{
     public bool Start(HostControl hostControl)
     {
          return true;
     }

     public bool Stop(HostControl hostControl) 
     {
          hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));
          return true;
     }
}

答案 1 :(得分:0)

类似于启动超时

x.SetStopTimeout(TimeSpan.FromMinutes(1));