保持 Windows 服务 运行 没有计时器

Keep a Windows Service running without a timer

目前,我看到的 C# 中 Windows 服务的唯一示例是计时器每 x 秒运行一次方法 - 例如检查文件更改。

我想知道是否有可能(如果可能的话使用示例代码)在没有计时器的情况下保留 Windows 服务 运行 而只是让服务监听事件 - 在同一个控制台应用程序仍然可以侦听事件并避免使用 Console.ReadLine() 关闭而不需要计时器的方式。

我基本上是在寻找一种方法来避免事件发生和执行操作之间的 x 秒延迟。

windows 服务不需要创建计时器来保持 运行。它可以建立文件观察器 Using FileSystemWatcher to monitor a directory 或启动异步套接字监听器。

这是一个简单的基于 TPL 的 listener/responder,无需将线程专用于进程。

private TcpListener _listener;

public void OnStart(CommandLineParser commandLine)
{
    _listener = new TcpListener(IPAddress.Any, commandLine.Port);
    _listener.Start();
    Task.Run((Func<Task>) Listen);
}

private async Task Listen()
{
    IMessageHandler handler = MessageHandler.Instance;

    while (true)
    {
        var client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);

        // Without the await here, the thread will run free
        var task = ProcessMessage(client);
    }
}

public void OnStop()
{
    _listener.Stop();
}

public async Task ProcessMessage(TcpClient client)
{
    try
    {
        using (var stream = client.GetStream())
        {
            var message = await SimpleMessage.DecodeAsync(stream);
            _handler.MessageReceived(message);
        }
    }
    catch (Exception e)
    {
        _handler.MessageError(e);
    }
    finally
    {
        (client as IDisposable).Dispose();
    }
}

这些都不需要计时器