C#,WinForm计时器,可以拓展循环执行某个方法

        bool isRunning = true;//用来改变计时状态
        Thread td;
        private void Form1_Load(object sender, EventArgs e)
        {
            btnEnd.Enabled = false;
        }
        #region 计时
        void TimeTask()
        {
            try
            {
                double timeCal = 0;
                while (isRunning)
                {
                    Thread.Sleep(1000);//休眠1000毫秒
                    timeCal++;
                    this.label1.BeginInvoke((EventHandler)(delegate
                    {
                        this.label1.Text = TimeSpan.FromSeconds(timeCal).ToString(@"hh\:mm\:ss");
                        //这里是关键
                    }));
                    //这里可以放其它方法 即循环一次执行一次
                }
            }
            catch (Exception ex)
            {
            }
        }
        #endregion

        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            btnEnd.Enabled = true;
            isRunning = true;//控制计时
            td = new Thread(TimeTask);//开新的线程
            td.IsBackground = true;
            if (!td.IsAlive)//线程运行状态
            {
                td.Start();
            }            
        }

        private void btnEnd_Click(object sender, EventArgs e)
        {
            td.Abort();
            btnStart.Enabled = true;
            btnEnd.Enabled = false;
            isRunning = false;
        }

评论