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 doQuery1
if necessary, but it's using an OdbcConnection
and data reader to get a single integer result then it's serializing it with Newtonsoft.Json
and sending it using Pubnub.publish()
. I'm hoping though that this is something obvious I'm just missing in the btnQuery1Start_Click()
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...)
See more on this question at Stackoverflow