一、C# Thread类的基本用法
通过System.Threading.Thread类可以开始新的线程,并在线程堆栈中运行静态或实例方法。可以通过Thread类的的构造方法传递一个无参数,并且不返回值(返回void)的委托(ThreadStart),这个委托的定义如下:
[ComVisibleAttribute(true)]
public delegate void ThreadStart()
我们可以通过如下的方法来建立并运行一个线程。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;
namespace MyThread { class Program { public static void myStaticThreadMethod() { Console.WriteLine("myStaticThreadMethod"); } static void Main(string[] args) { Thread thread1 = new Thread(myStaticThreadMethod); thread1.Start(); // 只要使用Start方法,线程才会运行 } } }
除了运行静态的方法,还可以在线程中运行实例方法,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;
namespace MyThread { class Program { public void myThreadMethod() { Console.WriteLine("myThreadMethod"); } static void Main(string[] args) { Thread thread2 = new Thread(new Program().myThreadMethod); thread2.Start(); } } }
如果读者的方法很简单,或出去某种目的,也可以通过匿名委托或Lambda表达式来为Thread的构造方法赋值,代码如下:
Thread thread3 = new Thread(delegate() { Console.WriteLine("匿名委托"); }); thread3.Start(); Thread thread4 = new Thread(( ) => { Console.WriteLine("Lambda表达式"); }); thread4.Start();
其中Lambda表达式前面的( )表示没有参数。
为了区分不同的线程,还可以为Thread类的Name属性赋值,代码如下:
Thread thread5 = new Thread(()=>{ Console.WriteLine(Thread.CurrentThread.Name); }); thread5.Name = "我的Lamdba"; thread5.Start();
如果将上面thread1至thread5放到一起执行,由于系统对线程的调度不同,输出的结果是不定的,如图1是一种可能的输出结果。

二、 定义一个线程类
我们可以将Thread类封装在一个MyThread类中,以使任何从MyThread继承的类都具有多线程能力。MyThread类的代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MyThread { abstract class MyThread { Thread thread = null;
abstract public void run();
public void start() { if (thread == null) thread = new Thread(run); thread.Start(); } } }
可以用下面的代码来使用MyThread类。
class NewThread : MyThread { override public void run() { Console.WriteLine("使用MyThread建立并运行线程"); } }
static void Main(string[] args) {
NewThread nt = new NewThread(); nt.start(); }
我们还可以利用MyThread来为线程传递任意复杂的参数。详细内容见下节。
三、C# Thread类:为线程传递参数
Thread类有一个带参数的委托类型的重载形式。这个委托的定义如下:
[ComVisibleAttribute(false)]
public delegate void ParameterizedThreadStart(Object obj)
这个TkhIzxkk9^jZ[# |