WPF、WinForm(C#)多线程编程并更新界面(UI)

来源:互联网 发布:国外发展人工智能吗 编辑:程序博客网 时间:2024/05/02 00:13
using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Linq;using System.Windows.Forms;using System.Threading;namespace doWorker{    public partial class Form1 : Form    {        delegate void MyDelegate(int value);        Thread t;        int i = 0;        public Form1()        {            InitializeComponent();        }        // 在新的线程中做“需要长时间做的”工作        private void button1_Click(object sender, EventArgs e)        {            t = new Thread(doWork);            t.Start();        }        // 要长时间做的工作        void doWork()        {            MyDelegate d = new MyDelegate(setValue);            while (true)            {                ++i;                //---WinForm--                this.Invoke(d, i);                //----WPF---added by wonsoft.cn---                this.Dispatcher.Invoke(d, i);                Thread.Sleep(100);            }        }        // 更新用户界面        void setValue(int value)            {            label1.Text = value.ToString();        }        // 终止线程的执行        private void button2_Click(object sender, EventArgs e)        {            t.Abort();        }    }}


多线程中子线程更新主线程ui简单实例

原帖:http://bbs.csdn.net/topics/350207091


0 0
原创粉丝点击