Andrew
Andrew

Reputation: 2539

Timer speeding up

I wrote a simple WinForm program in C# that displays the time, updating every second by creating an event. Although it starts off fine, after some time I notice that it's updating more quickly than every second. As more time passes, it continues to increase its updating speed. Any thoughts?

public static void Update(){
    if(!Pause) {
        aTimer = new System.Timers.Timer(1000);
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;
    }
}

private static void OnTimedEvent(object source,ElapsedEventArgs e) {
        Form1obj.updateLabel1(DateTime.Now.ToString());
}

In my Form class:

public void updateLabel1(string msg) {

    if (this.label1.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(updateLabel1);
        this.Invoke(d, new object[] { msg });
    }
    else
        this.label1.Text = msg;

}

Upvotes: 1

Views: 762

Answers (1)

thekip
thekip

Reputation: 3768

If you call update multiple times you will be subscribing multiple times to the same event.

So make sure you only do the
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

once (when the page is constructed for example)

Upvotes: 2

Related Questions