.NET将关于多线程的功能定义在System.Threading名字空间中。因此,要使用多线程,必须先声明引用此名字空间(using System.Threading;)。
a.启动线程
顾名思义,“启动线程”就是新建并启动一个线程的意思,如下代码可实现:
Thread thread1 = new Thread(new ThreadStart( Count));</div>
其中的 Count 是将要被新线程执行的函数。
b.杀死线程
“杀死线程”就是将一线程斩草除根,为了不白费力气,在杀死一个线程前最好先判断它是否还活着(通过 IsAlive 属性),然后就可以调用 Abort 方法来杀死此线程。
c.暂停线程
它的意思就是让一个正在运行的线程休眠一段时间。如 thread.Sleep(1000); 就是让线程休眠1秒钟。
d.优先级
这个用不着解释了。Thread类中hreadPRiority属性,它用来设置优先级,但不能保证操作系统会接受该优先级。一个线程的优先级可分为5种:Normal, AboveNormal, BelowNormal, Highest, Lowest。具体实现例子如下:
thread.Priority = ThreadPriority.Highest;</div>
e.挂起线程
Thread类的Suspend方法用来挂起线程,直到调用Resume,此线程才可以继续执行。如果线程已经挂起,那就不会起作用。
if (thread.ThreadState = ThreadState.Running) { thread.Suspend(); }</div>
f.恢复线程
用来恢复已经挂起的线程,以让它继续执行,如果线程没挂起,也不会起作用。
if (thread.ThreadState = ThreadState.Suspended) { thread.Resume(); }</div>
下面将列出一个例子,以说明简单的线程处理功能。此例子来自于帮助文档。
using System; using System.Threading; // Simple threading scenario: Start a static method running // on a second thread. public class ThreadExample { // The ThreadProc method is called when the thread starts. // It loops ten times, writing to the console and yielding // the rest of its time slice each time, and then ends. public static void ThreadProc() { for (int i = 0; i < 10; i++) { Console.WriteLine("ThreadProc: {0}", i); // Yield the rest of the time slice. Thread.Sleep(0); } } public static void Main() { Console.WriteLine("Main thread: Start a second thread."); // The constructor for the Thread class requires a ThreadStart // delegate that represents the method to be executed on the // thread. C# simplifies the creation of this delegate. Thread t = new Thread(new ThreadStart(ThreadProc)); // Start ThreadProc. On a uniprocessor, the thread does not get // any processor time until the main thread yields. Uncomment // the Thread.Sleep that follows t.Start() to see the difference. t.Start(); //Thread.Sleep(0); for (int i = 0; i < 4; i++) { Console.WriteLine("Main thread: Do some work."); Thread.Sleep(0); } Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends."); t.Join(); Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program."); Console.ReadLine(); } }</div>
此代码产生的输出类似如下内容:
Main thread: Start a second thread. Main thread: Do some work. ThreadProc: 0 Main thread: Do some work. ThreadProc: 1 Main thread: Do some work. ThreadProc: 2 Main thread: Do some work. ThreadProc: 3 Main thread: Call Join(), to wait until ThreadProc ends. ThreadProc: 4 ThreadProc: 5 ThreadProc: 6 ThreadProc: 7 ThreadProc: 8 ThreadProc: 9 Main thread: ThreadProc.Join has returned. Press Enter to end program.</div>
在Visul C#中System.Threading 命名空间提供一些使得可以进行多线程编程的类和接口,其中线程的创建有以下三种方法:Thread、ThreadPool、Timer。下面就它们的使用方法逐个作一简单介绍。
一、Thread
这也许是最复杂的方法,但它提供了对线程的各种灵活控制。首先你必须使用它的构造函数创建一个线程实例,它的参数比较简单,只有一个ThreadStart 委托:public Thread(ThreadStart start);然后调用Start()启动它,当然你可以利用它的Priority属性来设置或获得它的运行优先级(enum ThreadPriority: Normal、 Lowest、 Highest、 BelowNormal、 AboveNormal)。
下例首先生成了两个线程实例t1和t2,然后分别设置它们的优先级,接着启动两线程(两线程基本一样,只不过它们输出不一样,t1为“1”,t2为“2”,根据它们各自输出字符个数比可大致看出它们占用CPU时间之比,这也反映出了它们各自的优先级)。
static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(Thread1)); Thread t2 = new Thread(new ThreadStart(Thread2)); t1.Priority = ThreadPriority.BelowNormal ; t2.Priority = ThreadPriority.Lowest ; t1.Start(); t2.Start(); } public static void Thread1() { for (int i = 1; i < 1000; i++) {//每运行一个循环就写一个“1” dosth(); Console.Write("1"); } } public static void Thread2() { for (int i = 0; i < 1000; i++) {//每运行一个循环就写一个“2” dosth(); Console.Write("2"); } } public static void dosth() {//用来模拟复杂运算 for (int j = 0; j < 10000000; j++) { int a=15; a = a*a*a*a; } }</div>
以上程序运行结果为:
11111111111111111111111111111111111111111121111111111111111111111111111111111111111112
11111111111111111111111111111111111111111121111111111111111111111111111111111111111112
11111111111111111111111111111111111111111121111111111111111111111111111111111111111112
从以上结果我们可以看出,t1线程所占用CPU的时间远比t2的多,这是因为t1的优先级比t2的高,若我们把t1和t2的优先级都设为Normal,结果见下:
121211221212121212121212121212121212121212121212121212121212121212121
212121212121212121212121212121212121212121212121212121212121212121212
121212121212121212
从上例我们可看出,它的构造类似于win32的工作线程,但更加简单,只需把线程要调用的函数作为委托,然后把委托作为参数构造线程实例即可。当调用Start()启动后,便会调用相应的函数,从那函数第一行开始执行。
接下来我们结合线程的ThreadState属性来了解线程的控制。ThreadState是一个枚举类型,它反映的是线程所处的状态。当一个Thread实例刚创建时,它的ThreadState是Unstarted;当此线程被调用Start()启动之后,它的ThreadState是 Running; 在此线程启动之后,如果想让它暂停(阻塞),可以调用Thread.Sleep() 方法,它有两个重载方法(Sleep(int )、Sleep(Timespan )),只不过是表示时间量的格式不同而已,当在某线程内调用此函数时,它表示此线程将阻塞一段时间(时间是由传递给 Sleep 的毫秒数或Timespan决定的,但若参数为0则表示挂起此线程以使其它线程能够执行,指定 Infinite 以无限期阻塞线程),此时它的ThreadState将变为WaitSleepJoin,另外值得注意一点的是Sleep()函数被定义为了static?! 这也意味着它不能和某个线程实例结合起来用,也即不存在类似于t1.Sleep(10)的调用!正是如此,Sleep()函数只能由需“Sleep”的线程自己调用,不允许其它线程调用,正如when to Sleep是个人私事不能由它人决定。但是当某线程处于WaitSleepJoin状态而又不得不唤醒它时,可使用Thread.Interrupt 方法 ,它将在线程上引发ThreadInterruptedException,下面我们先看一个例子(注意Sleep的调用方法):
static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(Thread1)); t1.Start(); t1.Interrupt (); E.WaitOne (); t1.Interrupt (); t1.Join(); Console.WriteLine(“t1 is end”); } static AutoResetEvent E = new AutoResetEvent(false); public static void Thread1() { try {//从参数可看出将导致休眠 Thread.Sleep(Timeout.Infinite); } catch(System.Threading.ThreadInterruptedException e) {//中断处理程序 Console.WriteLine (" 1st interrupt"); } E.Set (); try {// 休眠 Thread.Sleep(Timeout.Infinite ); }