Thread类在命名空间System.Threading里定义。Thread的Priority有5种,AboveNormal、BelowNormal、Normal、Highest和Lowest。
Thread构造函数,有Thread(new ThreadStart(method))。Thread有Start()使线程改变为就绪状态,有IsAlive()判断线程是否存在,有Abort()撤销线程对象,有Sleep()休眠,有Suspend()使线程挂起状态,有Resume()重新运行。
using System.Threading; delegate void dFunc(string text); dFunc dFun1; private Thread thread; private void button1_Click(object sender, EventArgs e) { thread = new Thread(new ThreadStart(fun)); label1.Text = "0"; thread.Start(); button1.Enabled=false; button2.Enabled=true; } private void button2_Click(object sender, EventArgs e) { if(thread.Abort()) { button1.Enabled=true; button2.Enabled=false; } } public void fun() { while(true) { int x = Convert.ToInt32(label1.Text); x++; string s = Convet.ToString(); label1.Invoke(dFun1,new object[]{s}); Thread.Sleep(1000); } } private void Form1_FormClosing(object sender,FormClosingEventArgs e) { if(thread.IsAlive) thread.Abort(); }