Hi,
To better understand the use of Timer and Events, I have built a mini application that is supposed to write the time every preset interval, using the Timer class.
It works for me, except that I get the writing doubled each time.
I have tried hard to understand the reason, but for no avail.
Can anyone run the attached small app and let me know what have I done wrong, or how to make it write the time one per line?
Thanks in advnce
Loading
Zoran HorvatPosted Nov 27, 2010, 4:56 PM
rate.Tick += new EventHandler(writeData);
This means that you've subscribed to Tick event as many times as timer ticked. Results of this situation become difficult to track, because writeData toggles start/stop indicator whenever entered - now it enters once the first time, twice the second time switching the timer off but first entrance started timer again, and so on. A bit untraceable kind of code.
Also, you should not call btnStartStop_Click(sender, e); from writeData because sender and e from writeData do not apply to btnStartStop_Click, although it compiles.
To correct the issue, do the following:
1. Subscribe to Tick event only at the same place where you instantiate the timer. Instantiating the object as you did is a bit troublesome (I personally never use it). Better off, create timer in constructor, and subscribe to Tick event there.
2. Create a new method which starts timer. Call it from btnStartStop_Click when applicable, and call it from writeData.
CrishPosted Nov 29, 2010, 7:29 AM
SamPosted Nov 28, 2010, 1:45 AM
A perfect answer that solved my problem.