我正尝试在Windows服务中使用计时器。该服务能够启动和停止,并且在发生这种情况时我会向事件日志写入内容,这是有效的。我的问题是,我也想使用一个定时器,每次timeElapsed事件被触发时,定时器都会继续运行并向事件日志写入内容。在长时间运行的Windows服务中使用计时器
编辑:(我改变了代码,因此定时器是一个场,但依然没有结果,我所期望的,在事件日志中没有日志项)
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和 Best Timer for using in a Windows service
但是这些解决方案似乎并没有解决我的问题。
欢迎任何建议!
我强烈建议你不要使用'System.Timers.Timer',因为它会吞噬异常,隐藏错误。如果您的Elapsed事件发生异常,您永远不会知道。请参阅http:// blog。mischel.com/2011/05/19/swallowing-exceptions-is-hiding-bugs/。你应该1)用'try/catch'保护你的事件处理程序,2)使用'System.Threading.Timer'。 –
@JimMischel我刚刚发现这实际上是我的问题,现在我看到您的评论。它只是吞下一个例外,因为它没有奏效。 System.Threading.Timer是否修复了这一切? –
'System.Threading.Timer'不会吞下异常,这会让您知道您的处理程序中有问题。真正的解决方案是非常小心地处理你的定时器事件处理程序中的异常。 –