揭秘委托与多线程使用

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 WindowsFormsApplication1
{
    public partial class MainForm : Form
    {
        private delegate void ChangeTemperatureHander();
        public MainForm()
        {
            InitializeComponent();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            th = new Thread(this.Heating)

           //通过这个来说明该线程是主线程的子线程,当主线程关闭时,子线程一同关闭。

            th.IsBackground = true;
            th.Start();
        }

        private Thread th;
        private int temperature;
        private void Heating()
        {
            for (int i = 0; i < 100; i++)
            {
                temperature = i;

                //不能引用一个子线程来改变另外的一个线程的数据,故使用委托。
                this.Invoke(new ChangeTemperatureHander(OnChangeTemparature));
                Thread.Sleep(1000);
            }
        }
        private void OnChangeTemparature()
        {
            this.txtemperature.Text = temperature.ToString();
        }
    }
}

posted @ 2011-09-15 16:23  王永华  阅读(138)  评论(0编辑  收藏  举报