简体   繁体   English

当按下取消键(CTRL + C)强制停止服务时,控制台中的顶架

[英]Topshelf in console when cancel key (CTRL+C) pressed force stop service

I would like that Topshelf stops my service when I debug it in a console. 我希望Topshelf在控制台中调试时停止我的服务。

My code: 我的代码:

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;
        }
    }
}

But when I press CTRL+C it hangs in Microsoft.VisualStudio.HostingProcess.HostProc.WaitForThreadExit . 但是,当我按CTRL + C时,它将挂在Microsoft.VisualStudio.HostingProcess.HostProc.WaitForThreadExit

When I press CTRL+C I would like that host => host.StopService() is called immediately. 当我按CTRL + C时,我希望该host => host.StopService()被立即调用。

Is that possible? 那可能吗?

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

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

The most likely culprit is that your service's StartService method doesn't return control to Topshelf. 罪魁祸首是您服务的StartService方法没有将控制权返回给Topshelf。 What does your StartService do? 您的StartService做什么? It should only initialize any resources and start up your event loop/thread. 它仅应初始化任何资源并启动事件循环/线程。 Can you run service install start and get it to start up? 您可以运行service install start并启动它吗? If the service times out while starting up, it would also reinforce the idea that your start isn't returning. 如果该服务在启动时超时,那么还会使您的想法不再恢复。

its a known bug with .NET 4.0, there is a workaround but its nasty 它是.NET 4.0的已知错误,有一种解决方法,但它很讨厌

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

In VS2010, you need to: 在VS2010中,您需要:

  1. Go to your project property, then navigate to Debug pane, check 'Enable unmanaged code debugging'. 转到项目属性,然后导航到“调试”窗格,选中“启用非托管代码调试”。
  2. Toolbar Debug-> Exceptions -> then Uncheck the C++ Exceptions and the Win32 Exceptions. 工具栏Debug-> Exceptions->然后取消选中C ++ Exception和Win32 Exception。

在ServiceHost类中实现IDisposeable,添加Dispose方法,并处置所有线程对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM