[英]Windows service only executes once
我已經使用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()
。
將計時器的AutoReset屬性設置為true。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.