C#多线程 线程池
实例1:直接看看微软提供的代码
using System; using System.Threading; public class Example { public static void Main() { // Queue the task. ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); Console.WriteLine("Main thread does some work, then sleeps."); // If you comment out the Sleep, the main thread exits before // the thread pool task runs. The thread pool uses background // threads, which do not keep the application running. (This // is a simple example of a race condition.) Thread.Sleep(1000); Console.WriteLine("Main thread exits."); } // This thread procedure performs the task. static void ThreadProc(Object stateInfo) { // No state object was passed to QueueUserWorkItem, so // stateInfo is null. Console.WriteLine("Hello from the thread pool."); } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace Example { class ThreadPoolDemo { // 用于保存每个线程的计算结果 static int[] result = new int[10]; //注意:由于WaitCallback委托的声明带有参数, //所以将被调用的Fun方法必须带有参数,即:Fun(object obj)。 static void Fun(object obj) { int n = (int)obj; //计算阶乘 int fac = 1; for (int i = 1; i <= n; i++) { fac *= i; } //保存结果 result[n] = fac; } static void Main(string[] args) { //向线程池中排入9个工作线程 for (int i = 1; i <= 9; i++) { //QueueUserWorkItem()方法:将工作任务排入线程池。 ThreadPool.QueueUserWorkItem(new WaitCallback(Fun), i); // Fun 表示要执行的方法(与WaitCallback委托的声明必须一致)。 // i 为传递给Fun方法的参数(obj将接受)。 } //输出计算结果 for (int i = 1; i <= 9; i++) { Console.WriteLine("线程{0}: {0}! = {1}", i, result[i]); } } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。