定时器不会打勾

cpd*_*pdt 15 c# forms timer

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)

  • Windows.Forms.Timer在控制台应用程序中不起作用,或者在窗体外使用. (16认同)
  • 我真的不清楚这是如何解决这个问题的.行为完全相同(但我再也无法重现原始问题). (2认同)

小智 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)