Search code examples
c#.netmultithreadingwcf

C# Best way to schedule recurring task in an efficient windows service


I write a Windows Service in .Net Framework 4.0 and I need to schedule a recurring task inside. New task can only run if previous one is finished, so no tasks in parallel... All my task occurences work on same object (WCF Channel factory). A task takes almost 2 seconds to complete and may be scheduled every 2 seconds or every hour. My constraint is to have this Windows service as invisible/light as possible on memory and processor uses point of view...

I've already found these 2 ways:

  • Use a System.Timers.Timer with Autoreset to false => I've to implement an ElapsedEventHandler and pass my shared object (WCF Channel factory)
  • Use a never ending loop: not sure of mem/proc use in that state but no threads aspect to take care of.

Any suggestions?

Thanks and have a nice day!


Solution

  • For me was fine following: I'm started timer once, then in Tick method I will schedule next Tick call. Like this:

    private Timer _timer;
    
    //Interval in milliseconds
    int _interval = 1000;
    
    public void SetTimer()
    {   
        // this is System.Threading.Timer, of course
        _timer = new Timer(Tick, null, _interval, Timeout.Infinite);
    }
    
    private void Tick(object state)
    {
        try
        {
            // Put your code in here
        }   
        finally
        {
            _timer?.Change(_interval, Timeout.Infinite);
        }
    }
    
    // dont forget to dispose your timer using await _timer.DisposeAsync(); or _timer.Dispose();