【发布时间】:2011-05-10 01:51:25
【问题描述】:
我有一个定期需要做一些工作的 Windows 服务。所以我设置了一个 System.Timers.Timer 来做到这一点。让我们假设处理时间可能大于计时器间隔。让我们假设如果发生这种情况将是一件非常糟糕的事情。
为避免这种情况,我将 Timer 上的 AutoReset 设置为 false,然后在我的进程中调用 start。
public partial class Service : ServiceBase{
System.Timers.Timer timer;
public Service()
{
timer = new System.Timers.Timer();
//When autoreset is True there are reentrancy problme
timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}
protected override void OnStart(string[] args)
{
timer.Interval = 1;
timer.Start();
}
private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
{
Collection stuff = GetData();
LastChecked = DateTime.Now;
foreach (Object item in stuff)
{
item.Dosomthing(); //Do somthing should only be called once
}
TimeSpan ts = DateTime.Now.Subtract(LastChecked);
TimeSpan MaxWaitTime = TimeSpan.FromMinutes(5);
if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
timer.Interval = MaxWaitTime.Subtract(ts).TotalMilliseconds;
else
timer.Interval = 1;
timer.Start();
}
目前代码不会阻塞,因为我知道它是按顺序处理的,因为 AutoReset = false。但我可以做到这一点
lock(myLock)
{
Collection stuff = GetData();
LastChecked = DateTime.Now;
foreach (Object item in stuff)
{
item.Dosomthing(); //Do somthing should only be called once
}
}
编辑:澄清我的问题
我将服务设计为单线程,因此我不需要锁。如果我添加锁,我仍然在我的性能预算之内,所以性能不是不这样做的理由。
基本上,我正在权衡两个方面,并试图找出 Right Thing™ 是什么。 在“无锁”方面,我依靠一个装置来保证我的代码的正确性。在“锁定”方面,我将添加不必要的代码。
哪个更好?
【问题讨论】:
标签: c# .net windows-services