我一直在使用 System.Timer 来运行 Windows 服务,但遇到了计时器随机不触发的问题。我昨天检查了它,当它本应每 10 分钟触发一次时,它已经超过 2 小时没有触发。我在谷歌上阅读了这个,显然这是一个已知问题,答案是切换到 Threading.Timer。我之前没有使用过它,所以一直在寻找一些见解。我目前的代码如下:
using System;
using System.Timers;
using System.ServiceProcess;
namespace Code
{
public partial class Service : ServiceBase
{
Timer timer = new Timer();
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 10000;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
timer.Enabled = false;
// Run system code here
timer.Interval = 600000;
timer.Enabled = true;
}
}
基本上,这通常可以正常工作。系统启动计时器并在 10 秒后触发。它停止计时器,完成工作,将计时器重置 10 分钟并启用它。在大多数情况下,这始终有效,但如前所述,随机决定停止工作,可能是由于系统资源等原因。
如果有人可以帮助我将其转换为 Threading.Timer,将不胜感激。
谢谢, 克里斯
最佳答案
这是我最好的猜测 - 没有时间测试,抱歉 :(
using System;
using System.Threading;
using System.ServiceProcess;
namespace Code
{
public partial class Service : ServiceBase
{
Timer timer;
AutoResetEvent autoEvent;
bool stopped = true;
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
stopped = false;
TimerCallback tcb = new TimerCallback(OnElapsedTime);
timer = new Timer(tcb, null, 10000, 600000);
}
protected override void OnStop()
{
stopped = true;
timer.Dispose();
}
private void OnElapsedTime(Object stateInfo)
{
if (stopped)
return;
// Run system code here
}
}
}
关于c# - 将 C# System.Timer 转换为 Threading.Timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3297404/