Nic*_* N. 2 c# windows-services timer .net-4.0
我试图在Windows服务中使用计时器.该服务能够启动和停止,当这种情况发生时,我会在事件日志中写入内容,这是有效的.我的问题是我还想使用一个持续运行的计时器,并在每次触发timeElapsed事件时向事件日志写入内容.
编辑:(我更改了代码,所以计时器是一个字段,但仍然不是我期望的结果,事件日志中没有日志条目)
using System.Timers;
Run Code Online (Sandbox Code Playgroud)
初始化服务:
public Timer timer;
public MonitorService()
{
InitializeComponent();
timer = new Timer(10000);
//Some code that really doesn't matter
}
Run Code Online (Sandbox Code Playgroud)
开始活动
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;
Run Code Online (Sandbox Code Playgroud)
定时事件 :(这是不起作用的,每隔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);
}
Run Code Online (Sandbox Code Playgroud)
停止事件:
protected override void OnStop()
{
EventLogger.WriteEntry("Biztalk monitoring service stopped", EventLogEntryType.Warning);
}
Run Code Online (Sandbox Code Playgroud)
主要
对于那些想知道这是我在Program.cs中的主要方法的人:
///<summary>
///The main entry point for the application.
///</summary>
static void Main()
{
var servicesToRun = new ServiceBase[]
{
new MonitorService()
};
ServiceBase.Run(servicesToRun);
}
Run Code Online (Sandbox Code Playgroud)
已经问过了吗?确实是的!
我知道的事实,这个问题在前面已经喜欢这里问:有定时器的Windows服务和 最佳的定时器使用Windows服务
但这些解决方案似乎并没有解决我的问题.
欢迎任何建议!
您的计时器是OnStart方法的本地计时器.它不应该.它应该是您的服务类的一个字段,因此您不需要使用提示欺骗垃圾收集器.
编辑:你没有指定你using
的.确保使用Timer
您正在使用System.Timers.Timer,不是的System.Windows.Forms.Timer
.