Winform Timer用法,Invoke在Timer的事件中更新控件状态

System.Timers.Timer可以定时执行方法,在指定的时间间隔之后执行事件。

form窗体上放一个菜单,用于开始或者结束定时器Timer。

一个文本框,显示定时执行方法。

public partial class Form1 : Form
    {
        int count = 0;
        System.Timers.Timer timer;
        public Form1()
        {
            InitializeComponent();

            timer = new System.Timers.Timer();
            timer.Interval = 1000 * 5;
            timer.Elapsed += (x, y) =>
            {
                count++;

                InvokeMethod(string.Format("{0} count:{1}", DateTime.Now.ToString("HH:mm:ss"), count));
            };
        }

        private void InvokeMethod(string txt)
        {
            Action<string> invokeAction = new Action<string>(InvokeMethod);
            if (this.InvokeRequired)
            {
                this.Invoke(invokeAction, txt);
            }
            else
            {
                txtLog.Text += txt + Environment.NewLine;
            }
        }

        private void StartMenuItem_Click(object sender, EventArgs e)
        {
            if (StartMenuItem.Text == "开始")
            {
                txtLog.Text += string.Format("{0} {1}{2}", DateTime.Now.ToString("HH:mm:ss"),
                "开始运行...", Environment.NewLine);
                timer.Start();
                StartMenuItem.Text = "结束";
            }
            else
            {
                txtLog.Text += string.Format("{0} {1}{2}", DateTime.Now.ToString("HH:mm:ss"),
                "结束运行...", Environment.NewLine);
                timer.Stop();
                StartMenuItem.Text = "开始";
            }
        }
    }

运行截图如下:

Timer事件中更新窗体中文本框的内容,直接使用txtLog.Text +=...方式,会报异常“线程间操作无效: 从不是创建控件“txtLog”的线程访问它。”

因此用到了Invoke方法,这个方法用于“在拥有控件的基础窗口句柄的线程上,用指定的参数列表执行指定委托”。

解释一下,就是说文本框控件是在主线程上创建的,使用Invoke方法委托主线程更改文本框的内容。

 

posted @ 2017-06-24 17:20  pengtan  阅读(3551)  评论(0编辑  收藏  举报