TopShelf ConsoleHost结尾

时间:2017-12-12 14:35:10

标签: topshelf

我有一个基于TopShelf的控制台/ Windows服务应用程序。我通过运行控制台应用程序将其用作自动化脚本(在OctopusDeploy中)的一部分。但是,除非我按Ctrl-C,否则控制台应用程序不会退出。有没有办法禁用最后的按键检查​​?

代码:

class Program
{
    public static void Main()
    {
        HostFactory.Run(x =>
                {
                    x.Service<BatchJobService>(s =>
                                                   {
                                                       s.ConstructUsing(name => new BatchJobService());
                                                       s.WhenStarted((svc, hostControl) => svc.Start(hostControl));
                                                       s.WhenStopped((svc, hostControl) => svc.Stop(hostControl));
                                                   });
                    x.RunAsLocalSystem();
                    x.StartAutomatically();
                    x.SetDisplayName(serviceName);
                    x.SetServiceName(serviceName);
                });
    }
}

public class BatchJobService : ServiceControl
{
    private IDisposable host;

    public bool Start(HostControl hostControl)
    {
        if (hostControl is ConsoleRunHost)
        {
            **// Code for console app....
            return true; // Upon exit, program does not terminate**
        }

        // Start code for service...

        return true;
    }

    public bool Stop(HostControl hostControl)
    {
        if (hostControl is ConsoleRunHost)
        {
            return true;
        }

        // Stop code for service...
        return true;
    }
}

1 个答案:

答案 0 :(得分:0)

似乎不可能

我已经检查了topshelf源代码ConsoleRunHost.cs,无法避免等待ManualResetEvent

try
{
    _log.Debug("Starting up as a console application");

    _exit = new ManualResetEvent(false);
    _exitCode = TopshelfExitCode.Ok;

    Console.Title = _settings.DisplayName;
    Console.CancelKeyPress += HandleCancelKeyPress;

    if (!_serviceHandle.Start(this))
        throw new TopshelfException("The service failed to start (return false).");

    started = true;

    _log.InfoFormat("The {0} service is now running, press Control+C to exit.", _settings.ServiceName);

    _exit.WaitOne();
}

我想这是有目的的,因为Windows服务是长时间运行的进程,因此没有执行服务的Start方法并立即退出的感觉。

但是,我正在测试docfx工具如何在Azure构建管道中执行,因此我创建了启动docfx并退出的控制台,因此没有长时间运行的过程,但是需要Windows服务:)