c#委托和简单多线程

转自百度文库:

委托:

Public void setfunction (string s)

{

  For (int I;i<10;i++)

  {

     ……

   }

}

创建委托:

Delegate void setmain(string s);

Setmain setmaintest=new setmain(setfunction);

调用委托:

Label.Invoke(setmain,new object[]{i.Tostring()});

 

 

 

using System; 

using System.Threading; 

using System.Windows.Forms; 

namespace ThreadTest 

      public partial class Form1 : Form     { 

        private Thread thread1; //定义线程 

        delegate void set_Text(string s); //定义委托         

set_Text Set_Text; //定义委托 

        public Form1()         {

          InitializeComponent();        

     } 

        private void Form1_Load(object sender, EventArgs e)

        { 

            label1.Text = "0"; 

            Set_Text = new set_Text(set_lableText); //实例化

         } 

        private void button1_Click(object sender, EventArgs e) 

        { 

            thread1 = new Thread(new ThreadStart(run)); 

            thread1.Start(); 

        }

private void set_lableText(string s) //主线程调用的函数 

            label1.Text = s;

         } 

        private void run() 

        { 

            for (int i = 0; i < 101; i++)

             { 

                label1.Invoke(Set_Text, new object[] { i.ToString() }); //通过调用委托,来改变lable1的值 

                Thread.Sleep(1000); //线程休眠时间,单位是ms 

            } 

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

         { 

            if (thread1.IsAlive) //判断thread1是否存在,不能撤消一个不存在的线程,否则会引发异常 

            { 

                thread1.Abort(); //撤消thread1

             } 

        }

     }

 }

posted on 2013-09-08 08:31  Mis_Eur  阅读(277)  评论(0编辑  收藏  举报

导航