简单的线程池, 模版用


线程池在VS2005中似乎没有数量限制,  但是WaitHandle.WaitAll()函数限制64线程. 需要超过的话可以使用嵌套线程.


PS资料:
CodeProject一篇关于线程池数量限制的文章.
Changing the default limit of 25 threads of ThreadPool class




using System;
using System.Threading;
public class Fibonacci
{
    
public Fibonacci(int n, ManualResetEvent doneEvent)
    {
        _n 
= n;
        _doneEvent 
= doneEvent;
    }
    
// 线程池线程启动要调用的函数
    public void ThreadPoolCallback(Object threadContext)
    {
        
int threadIndex = (int)threadContext;
        Console.WriteLine(
"thread {0} started...", threadIndex);
        _fibOfN 
= Calculate(_n);
        Console.WriteLine(
"thread {0} result calculated...", threadIndex);
        _doneEvent.Set();
    }
    
// 线程计算过程 Recursive method that calculates the Nth Fibonacci number.
    public int Calculate(int n)
    {
        
if (n <= 1)
        {
            
return n;
        }
        
return Calculate(n - 1+ Calculate(n - 2);
    }
    
public int N { get { return _n; } }
    
private int _n;
    
public int FibOfN { get { return _fibOfN; } }
    
private int _fibOfN;
    
private ManualResetEvent _doneEvent;
}
public class ThreadPoolExample
{
    
static void Main()
    {
        
const int FibonacciCalculations = 64;
        
// 通知一个或多个正在等待的线程事件已经发生 ManualResetEvent
        ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
        Fibonacci[] fibArray 
= new Fibonacci[FibonacciCalculations];
        Random r 
= new Random();
        
// 开始使用线程池
        Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
        
for (int i = 0; i < FibonacciCalculations; i++)
        {
            doneEvents[i] 
= new ManualResetEvent(false);
            Fibonacci f 
= new Fibonacci(r.Next(2040), doneEvents[i]);
            fibArray[i] 
= f;
            ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
        }
        
// 等待线程池中所有计算完成
        WaitHandle.WaitAll(doneEvents);
        Console.WriteLine(
"All calculations are complete.");
        
// Display the results
        for (int i = 0; i < FibonacciCalculations; i++)
        {
            Fibonacci f 
= fibArray[i];
            Console.WriteLine(
"Fibonacci({0}) = {1}", f.N, f.FibOfN);
        }
        Console.ReadLine();
    }
}
原文地址:https://www.cnblogs.com/Bird/p/671880.html