Search code examples
c#winformsasynchronoustimer

Creating a background timer to run asynchronously


I'm really struggling with this. I'm creating a winforms application in visual studio and need a background timer that ticks once every half hour - the purpose of this is to pull down updates from a server.

I have tried a couple of different approaches but they have failed, either due to poor tutorial/examples, or to my own shortcomings in C#. I think it would be a waste of time to show you what I have tried so far as it seems what I tried was pretty far off the mark.

Does anyone know of a clear and simple way of implementing an asynchronous background timer that is easily understandable by a C# newbie?


Solution

  • // Create a 30 min timer 
    timer = new System.Timers.Timer(1800000);
    
    // Hook up the Elapsed event for the timer.
    timer.Elapsed += OnTimedEvent;
    
    timer.Enabled = true;
    ...
    
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        // do stuff
    }
    

    with the usual caveats of: timer won't be hugely accurate and might need to GC.KeepAlive(timer)

    See also: Why does a System.Timers.Timer survive GC but not System.Threading.Timer?