首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C#多線程編程進階(四):線程池自動管理核心API與完整示例代碼(二)

     編輯:關於C語言

ThreadPool 核心用法示例

完整控制台程序演示線程池佇列任務、同步等待、負載統計:

using System;
using System.Collections;
using System.Threading;

namespace ThreadExample {
    public class SomeState { public int Cookie; public SomeState(int c) { Cookie = c; } }

    public class Alpha {
        public Hashtable HashCount;
        public ManualResetEvent EventX;
        public static int Count = 0, MaxCount = 0;

        public Alpha(int max) { HashCount = new Hashtable(max); MaxCount = max; }

        public void Beta(Object state) {
            var s = (SomeState)state;
            Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(), s.Cookie);
            Console.WriteLine("HashCount.Count=={0}, Thread.CurrentThread.GetHashCode()=={1}", HashCount.Count, Thread.CurrentThread.GetHashCode());

            lock (HashCount) {
                if (!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode()))
                    HashCount.Add(Thread.CurrentThread.GetHashCode(), 0);
                HashCount[Thread.CurrentThread.GetHashCode()] = (int)HashCount[Thread.CurrentThread.GetHashCode()] + 1;
            }
            Thread.Sleep(2000);
            Interlocked.Increment(ref Count);
            if (Count == MaxCount) {
                Console.WriteLine(); Console.WriteLine("Setting eventX ");
                EventX.Set();
            }
        }
    }

    public class SimplePool {
        public static int Main() {
            Console.WriteLine("Thread Pool Sample:");
            bool w2k = false;
            int max = 10;
            var eventX = new ManualResetEvent(false);
            Console.WriteLine("Queuing {0} items to Thread Pool", max);
            var alpha = new Alpha(max) { EventX = eventX };

            Console.WriteLine("Queue to Thread Pool 0");
            try {
                ThreadPool.QueueUserWorkItem(new WaitCallback(alpha.Beta), new SomeState(0));
                w2k = true;
            } catch (NotSupportedException) {
                Console.WriteLine("These API's may fail when called on a non-Windows 2000 system.");
                w2k = false;
            }

            if (w2k) {
                for (int i = 1; i < max; i++) {
                    Console.WriteLine("Queue to Thread Pool {0}", i);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(alpha.Beta), new SomeState(i));
                }
                Console.WriteLine("Waiting for Thread Pool to drain");
                eventX.WaitOne(Timeout.Infinite, true);
                Console.WriteLine("Thread Pool has been drained (Event fired)");
                Console.WriteLine(); Console.WriteLine("Load across threads");
                foreach (object o in alpha.HashCount.Keys)
                    Console.WriteLine("{0} {1}", o, alpha.HashCount[o]);
            }
            Console.ReadLine();
            return 0;
        }
    }
}

關鍵點速覽

  • QueueUserWorkItem(WaitCallback, Object):入佇核心API,需Windows 2000+支持。
  • WaitCallback委托適配void Method(Object)簽名,SomeState攜帶業務參數。
  • ManualResetEvent實現主線程等待所有工作項完成(計數器+Interlocked.Increment)。
  • Hashtable記錄每個線程處理任務數,驗證複用情況。
  • 異常處理:捕獲NotSupportedException兼容舊系統。

此模式廣泛適用於批量短耗時異步任務(如並發請求、文件處理、數據入庫),是.NET高併發編程基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved