I have a windows service that periodically requires some work. So I created System.Timers.Timer for this. Assume that it is possible that the processing time may be longer than the timer interval. Let's also assume that it will be very bad if this happens.
To avoid this, I set AutoReset on Timer to false and then trigger a run in my process.
public partial class Service : ServiceBase{
System.Timers.Timer timer;
public Service()
{
timer = new System.Timers.Timer();
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();
}
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();
}
Currently, the code is not blocked, because I know that it is processed sequentially due to AutoReset = false. But I could do it along the way
lock(myLock)
{
Collection stuff = GetData();
LastChecked = DateTime.Now;
foreach (Object item in stuff)
{
item.Dosomthing();
}
}
EDIT: Clarification of my question
, . , , .
, , Right Thing ™.
" " . "Lock" .
?