我希望当我在控制台中调试服务时 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/