C#后台线程更新UI界面数据

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TaskUpdateUI
{
        ///


        /// 本例子用来说明如何从task多线程更新UI线程的内容
        ///

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        System.Timers.Timer Timer = new System.Timers.Timer(10000);//定义执行间隔10秒,单位毫秒,此timer是从后台重新建立一个线程,区别于winform中的timer控件。
        private void button1_Click(object sender, EventArgs e)
        {
            Timer.AutoReset = true;
           //使用timer定时更新例子 Timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
            Timer.Start();
           //for循环变更例子 Task task = Task.Factory.StartNew(()=>run());
        }

        void run()//要执行的内容,LIZI
        {
            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(100);
                this.Invoke(new Action(() => { this.richTextBox1.Text += "OK   " + DateTime.Now.ToString()+"\n"; }));// 此处 this.invoke使用匿名委托向主界面UI传递要更新的数据。

            }
        }

        private void Timer_Elapsed(object sender,System.Timers.ElapsedEventArgs elapsedEventArgs)//timer定时任务
        {
           // dosomething();执行的内容
            System.Threading.Thread.Sleep(1000);//模拟执行的内容耗时
            this.Invoke(new Action(() => { this.richTextBox1.Text += "OK   " + DateTime.Now.ToString() + "\n"; }));// 此处 this.invoke使用匿名委托向主界面UI传递要更新的数据。
        }
    }
}
效果:

C#后台线程更新UI界面数据_第1张图片

 

你可能感兴趣的:(C#,C#点点滴滴,C#,更新UI,多线程,委托更新主界面)