[英]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. 我在表单上有一个“开始和停止”按钮,用于启动和停止将数据发送到pubnub通道的重复SQL查询。 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()
. 如有必要,我可以发布
doQuery1
,但它使用OdbcConnection
和数据读取器来获取单个整数结果,然后使用Newtonsoft.Json
对其进行序列化,并使用Pubnub.publish()
发送。 I'm hoping though that this is something obvious I'm just missing in the btnQuery1Start_Click()
method above. 我希望这是显而易见的,但是我在上面的
btnQuery1Start_Click()
方法中只是缺少了。
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...) (我个人将其重写为
query1Timer.Elapsed += doQuery1;
但这是您的电话...)
每次按Start时,都会将事件处理程序添加到计时器中,但是在停止时,请勿将其删除。
Every time you click start you are executing the line: 每次单击开始时,您都在执行该行:
query1Timer.Elapsed += new ElapsedEventHandler(doQuery1);
This adds a new event handler each time it is called causing your doQuery1
method to be executed multiple times 每次调用时都会添加一个新的事件处理程序,从而导致多次执行
doQuery1
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.