定时器不会打勾
我的代码中有一个Windows.Forms.Timer
,我执行了3次。 但是,计时器根本没有调用tick函数。
private int count = 3; private timer; void Loopy(int times) { count = times; timer = new Timer(); timer.Interval = 1000; timer.Tick += new EventHandler(timer_Tick); timer.Start(); } void timer_Tick(object sender, EventArgs e) { count--; if (count == 0) timer.Stop(); else { // Do something here } }
从代码中的其他位置调用Loopy()
。
尝试使用System.Timers而不是Windows.Forms.Timer
void Loopy(int times) { count = times; timer = new Timer(1000); timer.Enabled = true; timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Start(); } void timer_Elapsed(object sender, ElapsedEventArgs e) { throw new NotImplementedException(); }
如果在不是主UI线程的线程中调用Loopy()方法,则计时器不会勾选。 如果要从代码中的任何位置调用此方法,则需要检查InvokeRequired
属性。 所以你的代码应该是这样的(假设代码是在一个表单中):
private void Loopy(int times) { if (this.InvokeRequired) { this.Invoke((MethodInvoker)delegate { Loopy(times); }); } else { count = times; timer = new Timer(); timer.Interval = 1000; timer.Tick += new EventHandler(timer_Tick); timer.Start(); } }
我不确定你做错了什么看起来是正确的,这段代码有效:看看它与你的比较。
public partial class Form1 : Form { private int count = 3; private Timer timer; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Loopy(count); } void Loopy(int times) { count = times; timer = new Timer(); timer.Interval = 1000; timer.Tick += new EventHandler(timer_Tick); timer.Start(); } void timer_Tick(object sender, EventArgs e) { count--; if (count == 0) timer.Stop(); else { // } } }
这是一个有效的Rx代码:
Observable.Interval(TimeSpan.FromSeconds(1)) .Take(3) .Subscribe(x=>Console.WriteLine("tick"));
当然,您可以在程序中订阅更有用的内容。
如果您使用的是Windows.Forms.Timer,那么应该使用以下内容。
//Declare Timer private Timer _timer= new Timer(); void Loopy(int _time) { _timer.Interval = _time; _timer.Enabled = true; _timer.Tick += new EventHandler(timer_Elapsed); _timer.Start(); } void timer_Elapsed(object sender, EventArgs e) { //Do your stuffs here }