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
}
}
Run Code Online (Sandbox Code Playgroud)
Loopy() 正在从代码中的其他地方调用.
Flo*_*iuc 44
尝试使用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();
}
Run Code Online (Sandbox Code Playgroud)
小智 7
如果在不是主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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31161 次 |
| 最近记录: |