多线程中应用委托

来源:互联网 发布:mysql取第一条记录 编辑:程序博客网 时间:2024/05/29 09:14

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

}

 

}

}

}

0 0