using System; using System.Diagnostics; using System.Threading; public class Fibonacci { private int _n; private int _fibOfN; private ManualResetEvent _doneEvent; public int N { get { return _n; } } public int FibOfN { get { return _fibOfN; } } // Constructor. public Fibonacci(int n, ManualResetEvent doneEvent) { _n = n; _doneEvent = doneEvent; } // Wrapper method for use with thread pool. 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 class c1902 { static void Main() { int start = 20; const int FibonacciCalculations = 20; // One event is used for each Fibonacci object. ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations]; Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations]; // Configure and start threads using ThreadPool. Console.WriteLine(DateTime.Now); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Console.WriteLine( "launching {0} tasks...", FibonacciCalculations); for (int i = 0; i < FibonacciCalculations; i++) { doneEvents[i] = new ManualResetEvent(false); Fibonacci f = new Fibonacci(start, doneEvents[i]); fibArray[i] = f; ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i); start++; } // Wait for all threads in pool to calculate. WaitHandle.WaitAll(doneEvents); Console.WriteLine("All calculations are complete."); stopwatch.Stop(); Console.WriteLine( "Parallel loop time in milliseconds: {0}", stopwatch.ElapsedMilliseconds); Console.WriteLine(DateTime.Now); // Display the results. for (int i= 0; i