#眉標=ThreadPool、foreach、Queue #副標= .NET執行緒控制技巧 #大標=運用ThreadPool發揮CPU運算能力 #作者=文/圖 吳剛志 #引言= ============= 程式1 不使用多執行緒,直接以迴圈來處理每一個工作 private static void SingleThreadSample (string[] files) { foreach (string file in files) { MakeThumb(file); } } ================ ============= 程式2 private static void MultiThreadSample1 (string[] files) { List threads = new List(); foreach (string file in files) { Thread t = new Thread(_MTS1); threads.Add(t); t.Start(file); } foreach (Thread t in threads) { t.Join(); } } private static void _MTS1(object state) { MakeThumb(state as string); } ================ ============= 程式3 private static void MultiThreadSample2 (string[] files, int threadCount) { Queue queue = new Queue(files); Thread[] threads = new Thread[threadCount]; for (int pos = 0; pos < threads.Length; pos++) { threads[pos] = new Thread(_MTS2); threads[pos].Start(queue); } foreach (Thread t in threads) { t.Join(); } } private static void _MTS2(object state) { Queue queue = (Queue)state; while(true) { string file = null; lock (queue) { if (queue.Count == 0) break; file = queue.Dequeue(); } MakeThumb(file); } } ================ ============= 程式4 private static void ThreadPoolSample (string[] files) { List waits = new List(); foreach (string file in files) { WorkItem wi = new WorkItem(file); waits.Add(wi.wait); ThreadPool.QueueUserWorkItem(_WCB, wi); } foreach (WaitHandle wait in waits) { wait.WaitOne(); } } private static void _WCB(object state) { WorkItem wi = state as WorkItem; MakeThumb(wi.file); wi.wait.Set(); } private class WorkItem { public WorkItem(string _file) { this.file = _file; } public string file = null; public ManualResetEvent wait = new ManualResetEvent(false); } ================