Search code examples
c#timer

System.Timers.Timer is not stopping


I have created a System.Timers.Timer and im quite new to it. So I have used the Windows Forms Timer before and now I want to use this timer for a console application.
My problem is that my timer is not stopping after one OnTimeEvent() and I don't know why.

class SortingSysFinal
{
    private static System.Timers.Timer aTimer;

    public static void Main(String[] args)
    {
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += OnTimedEvent;
        aTimer.Interval = 1000;
        aTimer.Enabled = true;
            
        Console.Read();
    }   
        
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
        aTimer.Stop();
    }
}

Solution

  • The problem is that in this line in your Main method:

    System.Timers.Timer aTimer = new System.Timers.Timer();
    

    You are creating a new local Timer object which is not the aTimer static member of your class. OnTimedEvent does get called, but it in this line: aTimer.Stop() it is attempting to use the aTimer static member which is null due to missing initialization (and therefore throws an exception).

    To fix it, change the line above to:

    aTimer = new System.Timers.Timer();
    

    This will initialize the static member of your class as I believe you intended, and will enable the handler to stop the timer.

    Note that System.Timers.Timer is not thread-safe. The Elapsed handler is called on a separate thread (see: documentation), and therefore you need to synchronize calline Stop() with a lock, or even better: use System.Threading.Timer instead.