C# System.Timers.Timer的簡(jiǎn)單使用

利用System.Timers.Timer實(shí)現(xiàn)實(shí)時(shí)更新

    public partial class Form1 : Form
    {
        //定義Timer類(lèi)
        System.Timers.Timer timer;
        //定義委托
        public delegate void SetControlValue(string value);
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitTimer();
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            timer.Start();
        }
        private void InitTimer()
        {
            int interval = 1000;
            timer = new System.Timers.Timer(interval);
            timer.AutoReset = true;
            timer.Enabled = true;
            //綁定事件,每隔一秒執(zhí)行一次此方法
            timer.Elapsed += new System.Timers.ElapsedEventHandler(MyMethod);
        }
        private void MyMethod(object sender,System.Timers.ElapsedEventArgs e)
        {
            string show = "";//需要現(xiàn)實(shí)的數(shù)據(jù)
            this.Invoke(new SetControlValue(SetTextBoxText), show);
        }
        /// <summary>
        /// 設(shè)置控件屬性Text
        /// </summary>
        /// <param name="value">文本內(nèi)容</param>
        private void SetTextBoxText(string value)
        {
            txt_result.Text = value;
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容