同步计时器以防止重叠 [英] Synchronizing a timer to prevent overlap
问题描述
我正在编写一个 Windows 服务,它每隔一段时间运行一个可变长度的活动(数据库扫描和更新).我需要频繁运行此任务,但要处理的代码并发运行多次并不安全.
I'm writing a Windows service that runs a variable length activity at intervals (a database scan and update). I need this task to run frequently, but the code to handle isn't safe to run multiple times concurrently.
我怎样才能最简单地设置一个计时器来每 30 秒运行一次任务,同时不重叠执行?(我假设 System.Threading.Timer
是这项工作的正确计时器,但可能是错误的).
How can I most simply set up a timer to run the task every 30 seconds while never overlapping executions? (I'm assuming System.Threading.Timer
is the correct timer for this job, but could be mistaken).
推荐答案
您可以使用 Timer 来实现,但您需要对数据库扫描和更新进行某种形式的锁定.一个简单的 lock
同步可能足以防止发生多次运行.
You could do it with a Timer, but you would need to have some form of locking on your database scan and update. A simple lock
to synchronize may be enough to prevent multiple runs from occurring.
话虽如此,最好在操作完成后启动一个计时器,只使用一次,然后停止它.下次操作后重新启动它.这将使您在事件之间有 30 秒(或 N 秒)的时间,没有重叠的机会,也没有锁定.
That being said, it might be better to start a timer AFTER you're operation is complete, and just use it one time, then stop it. Restart it after your next operation. This would give you 30 seconds (or N seconds) between events, with no chance of overlaps, and no locking.
示例:
System.Threading.Timer timer = null;
timer = new System.Threading.Timer((g) =>
{
Console.WriteLine(1); //do whatever
timer.Change(5000, Timeout.Infinite);
}, null, 0, Timeout.Infinite);
立即工作.....完成...等待 5 秒....立即工作.....完成...等待 5 秒....
这篇关于同步计时器以防止重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!