Timer won't tick

前端 未结 7 1777
一整个雨季
一整个雨季 2020-12-10 03:31

I have a Windows.Forms.Timer in my code, that I am executing 3 times. However, the timer isn\'t calling the tick function at all.

private int co         


        
7条回答
  •  长情又很酷
    2020-12-10 03:35

    If the method Loopy() is called in a thread that is not the main UI thread, then the timer won't tick. If you want to call this method from anywhere in the code then you need to check the InvokeRequired property. So your code should look like (assuming that the code is in a form):

            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();
                }
            }
    

提交回复
热议问题