CLR_via_C#.3rd 翻译[25.7 使用专用线程执行异步的计算限制操作]
25.7UsingaDedicatedThreadtoPerformanAsynchronousCompute-BoundOperation
使用专用线程执行异步的计算限制操作
本节将展示如何创建一个线程,并让它执行一次异步计算限制(asynchronouscompute-bound)操作。虽然会教你具体如何做,但强烈建议你避免采用这里展示的技术。相反,应该尽量使用CLR的线程池来执行异步计算限制操作
,这方面的详情将在第26章计算限制的异步操作讨论。
在某些情况下,你可能想显式创建一个线程来专门执行一个计算限制的操作。如果执行的代码要求线程处于一种特定的状态,而这种状态对于线程池线程来说是非同寻常的,就可考虑创建一个专用线程。例如,满足以下任何一个条件,就可以显式创建自己的线程:
■线程需要以非普通线程优先级运行
。所有线程池线程都以普通优先级运行;虽然可以更改这个优先级,但不建议那样做。另外,在不同的线程池操作之间,对优先级的更改是无法持续的。
■需要线程表现为前台线程,以免应用程序在线程结束它的任务之前终止
。更多的信息,请看这章的前台线程和后台线程部分。线程池线程始终是后台线程。如果CLR想终止进程,它们就可能被迫无法完成任务。
■受计算限制的任务需要长时间运行
;线程池为了判断是否需要创建一个额外的线程,所采用的逻辑比较复杂。直接为长时间运行的任务创建一个专用线程,就可以避开这个问题。
■要启动一个线程,并可能调用Thread的Abort
方法来提前终止它
(在第22章的CLR寄宿和应用程序域讨论)
为了创建一个专用线程,你要构造一个System.Threading.Thread类的实例,向它的构造器传递一个方法的名称。以下是Thread的构造器原型:
public sealed class Thread : CriticalFinalizerObject, ... {
public Thread(ParameterizedThreadStart start);
// Less commonly used constructors are not shown here
}
Start参数标识专用线程要执行的方法,这个方法必须和PrameterizedThreadStart
委托的签名匹配。
delegate void ParameterizedThreadStart(Object obj);
构造Thread对象是一个相对轻量级的操作,因为它并不实际创建一个操作系统线程。要实际创建操作系统线程,并让它执行回调方法,你必须调用Thread的Start方法,向它传递要作为回调方法的实参传递的对象(状态)。一下代码演示了如何创建一个专用线程,并让它异步调用一个方法。
using System;
using System.Threading;
public static class Program {
public static void Main() {
Console.WriteLine("Main thread: starting a dedicated thread " +
"to do an asynchronous operation");
Thread dedicatedThread = new Thread(ComputeBoundOp);
dedicatedThread.Start(5);
Console.WriteLine("Main thread: Doing other work here...");
Thread.Sleep(10000); // Simulating other work (10 seconds)
dedicatedThread.Join(); // Wait for thread to terminate
Console.WriteLine("Hit Enter to end this program...");
Console.ReadLine();
}
// This method's signature must match the ParameterizedThreadStart delegate
private static void ComputeBoundOp(Object state) {
// This method is executed by a dedicated thread
Console.WriteLine("In ComputeBoundOp: state={0}", state);
Thread.Sleep(1000); // Simulates other work (1 second)
// When this method returns, the dedicated thread dies
}
}
运行这些代码,会得到下面的输出:
Main thread: starting a dedicated thread to do an asynchronous operation
Main thread: Doing other work here...
In ComputeBoundOp: state=5
有时候,运行代码会得到下面的输出,因为我们无法控制windows是如何调度这两个线程的。
Main thread: starting a dedicated thread to do an asynchronous operation
In ComputeBoundOp: state=5
Main thread: Doing other work here...
注意,Main方法调用了Jion。Join方法造成调用线程阻塞当前执行的任何代码,直到dedicatedThread所代表的那个线程销毁或终止。