c# - 按下取消键 (CTRL+C) 时控制台中的 Topshelf 强制停止服务

标签 c# .net topshelf

我希望当我在控制台中调试服务时 Topshelf 停止我的服务。

我的代码:

public class Program
{
    private static ILog _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public static void Main(string[] args)
    {
        HostFactory.Run(Configure);
    }

    /// <summary>
    /// Configures the service host.
    /// </summary>
    /// <param name="cfg">The HostConfigurator</param>
    private static void Configure(HostConfigurator cfg)
    {
        try
        {
            cfg.Service<ServiceHost>(s =>
            {
                s.ConstructUsing(name => new ServiceHost());
                s.WhenStarted(host => host.StartService());
                s.WhenStopped(host => host.StopService());
            });

            cfg.RunAsLocalSystem();
            cfg.StartManually();
            cfg.SetDisplayName(DisplayName);
            cfg.SetServiceName(ServiceName);
            cfg.UseLog4Net();
        }
        catch (Exception ex)
        {
            _log.Fatal("Exception on Startup", ex);
            throw;
        }
    }
}

但是当我按 CTRL+C 时,它会卡在 Microsoft.VisualStudio.HostingProcess.HostProc.WaitForThreadExit 中。

当我按CTRL+C时,我希望立即调用host => host.StopService()

这可能吗?

最佳答案

应该可以通过向 Console.CancelKeyPress 事件添加事件处理程序来拦截 CTRL+C:

Console.CancelKeyPress += (s, e) => host.StopService();

关于c# - 按下取消键 (CTRL+C) 时控制台中的 Topshelf 强制停止服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21572007/

相关文章:

C# 服务器向 Java 客户端发送 UDP 数据包

c# - 了解 Parallel.Invoke,线程的创建和重用

.net - 如何防止 HttpWebRequest 的数据包碎片

c# - 是否可以运行托管在 Windows 服务中的 Orleans

c# - 具有 Unicode 字符的主机名在 Windows 8 中有效

c# - 使用通用 get 方法扩展 SerializedObject

c# - 这可以用最小起订量来模拟吗?

c# - 如何将流写入内存流?

.net - 如何在TopShelf中指定服务的命令行选项

c# - Topshelf开始陷入无限循环