多线程 非UI线程调用UI控件

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

namespace 多线程2
{
    public partial class Form2 : Form
    {
        delegate void SetUpTitle();
        public Form2()
        {
            InitializeComponent();
        }

        /// <summary>
        /// step1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form2_Load(object sender, EventArgs e)
        {
            Thread t = new Thread(Run);
            //非UI的线程调用UI的时候必然用到 窗体的Invok方法
            t.Start();
        }

        /// <summary>
        /// step2
        /// </summary>
        private void Run()
        {
            SetUpTitle setUp = new SetUpTitle(SetTitle);
            //InVoke中调用对UI的操作
            this.Invoke(setUp);
        }

        /// <summary>
        /// step3
        /// </summary>
        private void SetTitle()
        {
            for (var i = 0; i < 1000; i++)
            {
                this.Text = i.ToString();
            }
        }

    }
}

posted @ 2013-01-25 22:16  feidaochuanqing  阅读(198)  评论(0编辑  收藏  举报