在没有计时器的情况下保持 Windows 服务运行

编程入门 行业动态 更新时间:2024-10-28 07:19:21
本文介绍了在没有计时器的情况下保持 Windows 服务运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

目前我看到的 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 11:18:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   情况下   Windows

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!