I have to block, even when I process sequentially

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();
    //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();





 }

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(); //Do somthing should only be called once
     }     

}

EDIT: Clarification of my question

, . , , .

, , Right Thing ™. " " . "Lock" .

?

0
3

, , , .

- , . , , , .

+2

lock, . - , .

, .

0

Like others, if it is a single thread, there is no need for blocking. Alternatively, you can skip the timer together:

        TimeSpan maxInterval = new TimeSpan(0, 10, 0);
        while(true)
        {
            DateTime startTime = DateTime.UtcNow;


            //Do lots and lots of work


            TimeSpan ts = DateTime.UtcNow - startTime;
            ts = (ts > maxInterval ? new TimeSpan(0) : maxInterval-ts);
            Thread.Sleep(ts);
        }
0
source

Source: https://habr.com/ru/post/1773708/


All Articles