【发布时间】: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