Scott Scott - 5 months ago 19
C# Question

Disabling and enabling a timer causes a second instance?

I have a Start and Stop button on a form that start and stop a repeating SQL query which sends data to a pubnub channel. When I fire up the form and click start, I see what I expect on the subscribed clients. However, if I click stop then start again, I now get duplicate data. A third time gives me triplicate data, etc. What is causing this? Here are the start and stop methods:

private void btnQuery1Start_Click(object sender, EventArgs e)

lblQuery1Status.Text = "Status: Running";
btnQuery1Start.Enabled = false;
txtQuery1Interval.Enabled = false;
btnQuery1Stop.Enabled = true;
query1Timer.Elapsed += new ElapsedEventHandler(doQuery1);
query1Timer.Interval = Convert.ToInt32(txtQuery1Interval.Text) * 1000;
query1Timer.Enabled = true;

private void btnQuery1Stop_Click(object sender, EventArgs e)
btnQuery1Start.Enabled = true;
btnQuery1Stop.Enabled = false;
txtQuery1Interval.Enabled = true;
query1Timer.Enabled = false;
lblQuery1Status.Text = "Status: Stopped";

I can post
if necessary, but it's using an
and data reader to get a single integer result then it's serializing it with
and sending it using
. I'm hoping though that this is something obvious I'm just missing in the
method above.


No, you have a single timer - but you're adding an event handler to it every time you click start:

query1Timer.Elapsed += new ElapsedEventHandler(doQuery1);

Just move that line into wherever you construct the timer, so it only gets added once, and it'll be fine.

(I'd personally rewrite it as query1Timer.Elapsed += doQuery1;, but that's your call...)