Search code examples
c#formstimer

Timer won't tick


I have a Windows.Forms.Timer in my code, that I am executing 3 times. However, the timer isn't calling the tick function at all.

private int count = 3;
private timer;
void Loopy(int times)
{
    count = times;
    timer = new Timer();
    timer.Interval = 1000;
    timer.Tick += new EventHandler(timer_Tick);
    timer.Start();
}

void timer_Tick(object sender, EventArgs e)
{
    count--;
    if (count == 0) timer.Stop();
    else
    {
        // Do something here
    }
}

Loopy() is being called from other places in the code.


Solution

  • Try using System.Timers instead of Windows.Forms.Timer

    void Loopy(int times)
    {
        count = times;
        timer = new Timer(1000);
        timer.Enabled = true;
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        timer.Start();
    }
    
    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        throw new NotImplementedException();
    }