一、Windows为什么要支持线程
Microsoft设计OS内核时,他们决定在一个进程(PRocess)中运行应用程序的每个实例。进程不过是应用程序的一个实例要使用的资源的一个集合。每个进程都赋予了一个虚拟地址空间,确保一个进程使用的代码和数据无法由另一个进行访问。这样就确保了应用程序集的健壮性,因为一个进程无法破坏另一个进程里的数据和代码。另外,进程是无法访问到OS的内核代码和数据。 如果一个应用程序进入死循环时,如果只是单核的CPU的,它会无限循环执行下去,不能执行其他代码,这样会使系统停止响应。对此,Microsoft拿出的一个解决方案——线程。线程的职责就是对CPU的虚拟化。Windows为每个进程都提供了该进程专用的线程(功能相当于一个CPU,可将线程理解成一个逻辑CPU)。如果应用程序的代码进入无限循环,与那个代码关联的进程会"冻结",但其他进程不会冻结,会继续执行。二、线程开销线程尽管非常强悍,但和一切虚拟化机制一样,线程会产生空间(内存耗用)和时间(运行时的执行性能)上的开销。public sealed class Thread : CriticalFinalizerobject,... { public Thread(ParameterizedThreadStart start); //这里没有列出不常用的构造器}
start参数标识专用线程要执行的方法,这个方法必须和ParameterizedThreadStart委托的签名匹配。
delegate void ParameterizedThreadStart(Oject obj);构造Thread对象是一个轻量级操作,因为它并不实际创建一个操作系统线程。要实际创建操作系统线程,并让它开始执行回调方法,必须调用Thread的Start方法,向它传递要作为回调方法的实参传递的对象(状态)。以下代码演示了如何创建一个专用线程,并让它异步调用一个方法:
internal static class FirstThread { public static void Go() { 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); // 模拟做其它工作(10 秒钟) dedicatedThread.Join(); // 等待线程终止 Console.ReadLine(); } // 这个方法的前面必须和ParametizedThreadStart委托匹配 private static void ComputeBoundOp(Object state) { // 这个方法由一个专用线程执行 Console.WriteLine("In ComputeBoundOp: state={0}", state); Thread.Sleep(1000); // 模拟其它任务(1 秒钟) // 这个方法返回后,专用线程将终止 }}在我的机器上编译运行,可能得到以下结果:Main thread: starting a dedicated thread to do an asynchronous operationMain thread: Doing other work here...In ComputeBoundOp: state=5 但有的时候运行上述代码,也可能得到以下结果,因为我无法控制Windows对两个线程进行调度的方式:Main thread: starting a dedicated thread to do an asynchronous operationIn ComputeBoundOp: state=5Main thread: Doing other work here... 注意Go()方法调用的Join。Join方法造成调用线程阻塞当前执行的任何代码,直到dedicatedThread所代表的那个线程销毁或终止。六、使用线程的理由使用线程有以下三方面的理由:
学习交流
热门图片
猜你喜欢的新闻
新闻热点 2019-10-23 09:17:05
2019-10-21 09:20:02
2019-10-21 09:00:12
2019-09-26 08:57:12
2019-09-25 08:46:36
2019-09-25 08:15:43
疑难解答 |
---|