【问题标题】:Windows service only executes onceWindows 服务只执行一次
【发布时间】:2016-10-21 20:50:24
【问题描述】:

我使用 TopShelf 编写了我的第一个 .Net 服务,但遇到了服务代码仅执行一次的问题。

我已将服务主配置如下

    private static void Main(string[] args)
    {
        HostFactory.Run(x =>
        {
            x.Service<ServiceProcess>(s =>
            {
                s.ConstructUsing(name => new ServiceProcess());
                s.WhenStarted(tc => tc.Start());
                s.WhenStopped(tc => tc.Stop());
            });

            x.StartAutomatically();
            x.RunAs(Username, Password);
        });
    }

而只运行一次的方法如下。

using System.Timers;

public class ServiceProcess
{
    private readonly Timer _timer;

    public ServiceProcess()
    {
        _timer = new Timer(1000) { AutoReset = false };
        _timer.Elapsed += (sender, eventArgs) => EventLog.WriteEntry(ServiceName, "It is " + DateTime.Now, EventLogEntryType.Information);
    }
}

我可以在事件日志中看到消息写入正确,但它只出现一次。由于这是最基本的配置,我不确定为什么这不起作用。我玩过时间并尝试添加异常处理,但最终它似乎根本不再运行。

请注意,我的 Start()Stop() 方法分别执行 _timer.Start()_timer.Stop()

【问题讨论】:

    标签: c# .net windows-services topshelf


    【解决方案1】:

    将计时器的 AutoReset 属性设置为 true。

    【讨论】:

    • 为我辩护的是,一位同事向我提供了不好的信息。 ;) 很高兴为您提供简单的积分。
    • 我想为任何寻找的人提供这个链接。这不是 TopShelf 特有的,而是一个服务属性:msdn.microsoft.com/en-us/library/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多