在没有计时器的情况下保持 Windows 服务运行 [英] Keep a Windows Service running without a timer

查看:44
本文介绍了在没有计时器的情况下保持 Windows 服务运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Currently the only examples of a Windows service in C# I have seen are where a timer runs through a method every x seconds - e.g. checking for file changes.

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

I'm wondering if it is possible (with example code if possible) to keep a Windows service running without a timer and instead just have a service listening for events - in the same way a console application can still listen for events and avoid closing with Console.ReadLine() without requiring a timer.

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

I am essentially looking for a way to avoid the x second delay between an event happening and an action being performed.

推荐答案

Windows 服务不需要创建计时器来保持运行.它可以建立一个文件观察器使用 FileSystemWatcher 来监测一个目录或启动一个异步套接字侦听器.

A windows service does not need to create a timer to keep running. It can either establish a file watcher Using FileSystemWatcher to monitor a directory or start an asynchronous socket listener.

这是一个简单的基于 TPL 的侦听器/响应器,无需将线程专用于进程.

Here is a simple TPL based listener/responder without needing to dedicate a thread to the process.

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

这些都不需要计时器

这篇关于在没有计时器的情况下保持 Windows 服务运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆