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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM