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方法委托主线程更改文本框的内容。

  • 相关阅读:
    指针常量 和 常量指针
    串口通讯
    C语言的抽象与函数指针2
    STM32 中常见错误 的处理方法
    串行通信之狂扯篇
    VMware中虚拟机网卡的四种模式
    VSFTP配置虚拟用户
    MySQL数据库备份命令
    rsync Linux系统下的数据镜像备份工具
    linux常用命令
  • 原文地址:https://www.cnblogs.com/tanpeng/p/7073879.html
Copyright © 2011-2022 走看看