zoukankan      html  css  js  c++  java
  • 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方法委托主线程更改文本框的内容。

  • 相关阅读:
    能飞英语学习软件学习实践
    英语学习方式总结与实践
    Hello World
    centos 7.6中搭建samba共享服务
    PHP漏洞全解(一)PHP网站的安全性问题
    MySQL查询语句练习题
    在PHP中使用CURL实现GET和POST请求的方法
    js数组的操作大全
    php四种基础算法:冒泡,选择,插入和快速排序法
    Linux查看端口使用状态及启动
  • 原文地址:https://www.cnblogs.com/tanpeng/p/7073879.html
Copyright © 2011-2022 走看看