Reputation: 13
i have a problem with my code :
System.Windows.Forms.Timer Timer1 = new System.Windows.Forms.Timer();
int TimeCount;
private void button1_Click(object sender, EventArgs e)
{
Timer1.Interval = 1000;
Timer1.Enabled = true;
TimeCount = 0;
Timer1.Tick += new EventHandler(TimerEventProcessor);
}
private void TimerEventProcessor(Object sender, EventArgs myEventArgs)
{
TimeCount = TimeCount + 1;
}
private void button2_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
TimeCount = 0;
}
At the first run, TimeCount will do steps well (1,2,3,4,5,....)
but if i button2 to stop, then button1 to restart, TimeCount steps will do (2,4,6,8,10,...)
and then if i repeat operation steps will do (3,6,9,....)
How to get my TimeCount int to correctly allways do (1,2,3,4,5,....) ?
Upvotes: 1
Views: 43
Reputation: 38767
This is a problem with how you're using event handler delegates:
Timer1.Tick += new EventHandler(TimerEventProcessor);
This adds a new handler (TimerEventProcessor
) to the list of delegate methods Tick
holds. So on each tick, the event will loop through the registered handlers and call them each in turn.
If you add a method to Tick
twice, it will get called twice. Add it three times, it will get called three times, and so on. Each time you click button1
you add another handler to the list.
I suggest moving Timer1.Tick += new EventHandler(TimerEventProcessor);
to the load event (e.g. Form_Load
) or to your constructor (public Form1()
). You only need to register the handler once.
Alternatively, in button2, deregister the handler:
Timer1.Tick -= new EventHandler(TimerEventProcessor);
Upvotes: 2