类库CLib里的类Class1:
using System;
using System.Collections.Generic;
using System.Text;namespace CLib
{
public class Class1
{
private System.Timers.Timer ti = new System.Timers.Timer(1000);
private int tis = 0; private void ti_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
tis++;
if (tis > 6)
{
ti.Enabled = false;
tis = 0;
}
else
{
ti.Enabled = true;
}
} public int t()
{
return tis;
} public void m()
{
ti.Elapsed += new System.Timers.ElapsedEventHandler(ti_Elapsed);
ti.AutoReset = false;
ti.Enabled = true;
}
}
}
主程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using CLib;namespace 测试
{
public partial class Form1 : Form
{
CLib.Class1 cl = new CLib.Class1();
private void button1_Click(object sender, EventArgs e)
{
cl.m();//启动CLib里的定时器
} private void button2_Click(object sender, EventArgs e)
{
int i = cl.t();
MessageBox.Show(i.ToString());//显示计数
}
}
}
当我第一次触发button1_Click时一切正常,但是当计时器停止后再次触发button1_Click有时候都没有执行ti_Elapsed里面的代码(我在tis++打的断点),而且在tis大于6后计时器仍然没有停止,请问怎么回事?要怎么处理?
using System;
using System.Collections.Generic;
using System.Text;namespace CLib
{
public class Class1
{
private System.Timers.Timer ti = new System.Timers.Timer(1000);
private int tis = 0; private void ti_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
tis++;
if (tis > 6)
{
ti.Enabled = false;
tis = 0;
}
else
{
ti.Enabled = true;
}
} public int t()
{
return tis;
} public void m()
{
ti.Elapsed += new System.Timers.ElapsedEventHandler(ti_Elapsed);
ti.AutoReset = false;
ti.Enabled = true;
}
}
}
主程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using CLib;namespace 测试
{
public partial class Form1 : Form
{
CLib.Class1 cl = new CLib.Class1();
private void button1_Click(object sender, EventArgs e)
{
cl.m();//启动CLib里的定时器
} private void button2_Click(object sender, EventArgs e)
{
int i = cl.t();
MessageBox.Show(i.ToString());//显示计数
}
}
}
当我第一次触发button1_Click时一切正常,但是当计时器停止后再次触发button1_Click有时候都没有执行ti_Elapsed里面的代码(我在tis++打的断点),而且在tis大于6后计时器仍然没有停止,请问怎么回事?要怎么处理?
根据我的理解, 这里是不是累加的?多个事件处理方法。导致不能停止。
去掉 ti.Elapsed += new System.Timers.ElapsedEventHandler(ti_Elapsed);
这一行第一次启动调用m()后面的调用 m2()方法应该可以达到预期目的。
在 ti.Elapsed += new System.Timers.ElapsedEventHandler(ti_Elapsed);
这一句的前面加一行代码ti.Elapsed -= new System.Timers.ElapsedEventHandler(ti_Elapsed);