2

当我在控制台中调试它时,我希望 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()立即调用它。

那可能吗?

4

5 回答 5

2

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

Console.CancelKeyPress += (s, e) => host.StopService();
于 2014-02-05T08:57:38.973 回答
1

最可能的罪魁祸首是您的服务StartService方法没有将控制权返回给 Topshelf。你是StartService做什么的?它应该只初始化任何资源并启动您的事件循环/线程。你能跑service install start起来让它启动吗?如果服务在启动时超时,它也会强化您的启动没有返回的想法。

于 2014-02-05T13:11:42.820 回答
0

它是 .NET 4.0 的一个已知错误,有一种解决方法,但它很讨厌

https://github.com/Topshelf/Topshelf/issues/10

于 2014-02-10T07:31:48.120 回答
0

在 VS2010 中,您需要:

  1. 转到您的项目属性,然后导航到“调试”窗格,选中“启用非托管代码调试”。
  2. 工具栏调试-> 异常-> 然后取消选中 C++ 异常和 Win32 异常。
于 2014-03-07T15:30:08.167 回答
0

在您的 ServiceHost 类中实现 IDisposeable,添加一个 Dispose 方法,并释放所有线程对象。

于 2018-05-31T14:32:24.310 回答