简体   繁体   English

Windows服务仅执行一次

[英]Windows service only executes once

I've written my first .Net Service using TopShelf and I'm experiencing an issue where the service code only executes a single time. 我已经使用TopShelf编写了我的第一个.Net服务,并且遇到了服务代码只能执行一次的问题。

I have configured the service main as follows 我已经如下配置了服务主体

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

And the method that runs only a single time is as follows. 并且仅运行一次的方法如下。

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

I can see in the event log that the message is written correctly but it only occurs a single time. 我可以在事件日志中看到消息已正确写入,但仅发生一次。 Since this is the most basic of configuration I'm not certain why this isn't working. 因为这是最基本的配置,所以我不确定为什么它不起作用。 I have played with the timing and attempted to add exception handling but ultimately it appears to simply not be running again. 我已经考虑了时间安排,并尝试添加异常处理,但最终它似乎根本不再运行。

Note that my Start() and Stop() methods are doing a _timer.Start() and _timer.Stop() respectively. 请注意,我的Start()Stop()方法分别在执行_timer.Start()_timer.Stop()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM