我正在尝试在 Windows 服务中使用计时器。该服务能够启动和停止,并且在发生这种情况时我会在事件日志中写入一些内容,这很有效。我的问题是,我还想使用一个持续运行的计时器,并在每次触发 timeElapsed 事件时向事件日志写入一些内容。
编辑:(我更改了代码,所以计时器是一个字段,但仍然不是我期望的结果,事件日志中没有日志条目)
using System.Timers;
初始化服务:
public Timer timer;
public MonitorService()
{
InitializeComponent();
timer = new Timer(10000);
//Some code that really doesn't matter
}
开始事件
protected override void OnStart(string[] args)
{
// Hook up the Elapsed event for the timer.
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Enabled = true;
timer.Start();
EventLogger.WriteEntry("Biztalk monitoring service started", EventLogEntryType.SuccessAudit);
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
// GC.KeepAlive(timer);
}
private int count =0;
定时事件:(这是行不通的,没有每 10 秒写入事件日志的条目,而我希望它会这样做)
// Specify what you want to happen when the Elapsed event is
// raised.
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Some other code that doesn't mather
count++;
EventLogger.WriteEntry(string.Format("TimerEvent has ran {0} times. Total time is: {1}", count, e.SignalTime), EventLogEntryType.Information);
}
停止事件:
protected override void OnStop()
{
EventLogger.WriteEntry("Biztalk monitoring service stopped", EventLogEntryType.Warning);
}
主要的
对于那些想知道这是我在 Program.cs 中的主要方法的人:
///<summary>
///The main entry point for the application.
///</summary>
static void Main()
{
var servicesToRun = new ServiceBase[]
{
new MonitorService()
};
ServiceBase.Run(servicesToRun);
}
已经问过了?确实是的!
我知道这个问题已经像这里一样早先被问过:Windows service with timer AND Best Timer for using in a Windows service
但这些解决方案似乎并不能解决我的问题。
欢迎任何建议!