25.6 CLR线程和Windows线程
虽然今天的一个CLR线程是直接对应于一个Windows线程,但Microsoft CLR团队保留了将来把它从Windows线程分离的权利。
25.7 使用专用线程执行异步的计算限制操作
满足一下任何一个条件,就可以显式创建自己的线程:
- 线程需要以非普通线程优先级运行。所有线程池线程都以普通优先级运行;虽然可以更改这个优先级,但不建议那样做。
- 需要线程表现为一个前台线程,防止应用程序在线程结束它的任务之前终止。线程池线程始终是后台线程。如果CLR想终止进程,它们就可能被迫无法完成任务。
- 要启动一个线程,并可能调用Thread的Abort方法来提前终止它。
using System;
using System.Threading;
namespace ThreadStudy
{
class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(Print));
thread1.Start();
Console.WriteLine("Here is running main thread~");
Console.WriteLine("Wait thread1 to execute completed~");
thread1.Join();
Console.WriteLine("Thread1 has executed completely~");
Console.WriteLine("Main thread has executed completely~");
}
static void Print()
{
Console.WriteLine("Here is running thread1~");
Thread.Sleep(2000);
Console.WriteLine("Hello world~");
}
}
}
执行输出:
Here is running main thread~
Wait thread1 to execute completed~
Here is running thread1~
Hello world~
Thread1 has executed completely~
Main thread has executed completely~
Press any key to continue . . .
构造Thread对象是一个轻量级操作,因为它并不实际创建一个操作系统线程。要实际创建操作系统线程,并让它开始执行回调方法,必须调用Thread的Start方法,向它传递要作为回调方法的实参传递的对象(状态)。
Thread的Join()方法造成调用线程阻塞当前执行的任何代码,直到调用线程所代表的那个线程销毁或终止。