標籤:
執行個體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]); } } }}
C#多線程 線程池