How to let Timer skip tick if the previous thread is still busy

后端 未结 8 1632
攒了一身酷
攒了一身酷 2020-12-01 11:28

I created a windows service, that is supposed to check a certain table in the db for new rows every 60 seconds. For every new row that was added, I need to do some heavy pro

相关标签:
8条回答
  • 2020-12-01 12:00

    There's quite a neat way of solving this with Reactive Extensions. Here's the code, and you can read a fuller explanation here: http://www.zerobugbuild.com/?p=259

    public static IDisposable ScheduleRecurringAction(
        this IScheduler scheduler,
        TimeSpan interval,
        Action action)
    {
        return scheduler.Schedule(
            interval, scheduleNext =>
        {
            action();
            scheduleNext(interval);
        });
    }
    

    And you could use it like this:

    TimeSpan interval = TimeSpan.FromSeconds(5);
    Action work = () => Console.WriteLine("Doing some work...");
    
    var schedule = Scheduler.Default.ScheduleRecurringAction(interval, work);          
    
    Console.WriteLine("Press return to stop.");
    Console.ReadLine();
    schedule.Dispose();
    
    0 讨论(0)
  • 2020-12-01 12:02

    A similar variation on other answers, that allows the timer to keep ticking and only do the work when the lock can be obtained, instead of stopping the timer.

    Put this in the elapsed event handler:

    if (Monitor.TryEnter(locker)
    {
        try
        {
            // Do your work here.
        }
        finally
        {
            Monitor.Exit(locker);
        }
    }
    
    0 讨论(0)
提交回复
热议问题