1 //Copyright (C) Microsoft Corporation. All rights reserved. 2 3 using System; 4 using System.Threading; 5 6 // The Fibonacci class provides an interface for using an auxiliary 7 // thread to perform the lengthy Fibonacci(N) calculation. 8 // N is provided to the Fibonacci constructor, along with an 9 // event that the object signals when the operation is complete. 10 // The result can then be retrieved with the FibOfN property. 11 public class Fibonacci 12 { 13 public Fibonacci(int n, ManualResetEvent doneEvent) 14 { 15 _n = n; 16 _doneEvent = doneEvent; 17 } 18 19 // Wrapper method for use with thread pool. 20 public void ThreadPoolCallback(Object threadContext) 21 { 22 int threadIndex = (int)threadContext; 23 Console.WriteLine("thread {0} started...", threadIndex); 24 _fibOfN = Calculate(_n); 25 Console.WriteLine("thread {0} result calculated...", threadIndex); 26 _doneEvent.Set(); 27 } 28 29 // Recursive method that calculates the Nth Fibonacci number. 30 public int Calculate(int n) 31 { 32 if (n <= 1) 33 { 34 return n; 35 } 36 else 37 { 38 return Calculate(n - 1) + Calculate(n - 2); 39 } 40 } 41 42 public int N { get { return _n; } } 43 private int _n; 44 45 public int FibOfN { get { return _fibOfN; } } 46 private int _fibOfN; 47 48 ManualResetEvent _doneEvent; 49 } 50 51 public class ThreadPoolExample 52 { 53 static void Main44() 54 { 55 const int FibonacciCalculations = 10; 56 57 // One event is used for each Fibonacci object 58 var doneEvents = new ManualResetEvent[FibonacciCalculations]; 59 var fibArray = new Fibonacci[FibonacciCalculations]; 60 var r = new Random(); 61 62 // Configure and launch threads using ThreadPool: 63 Console.WriteLine("launching {0} tasks...", FibonacciCalculations); 64 for (int i = 0; i < FibonacciCalculations; i++) 65 { 66 doneEvents[i] = new ManualResetEvent(false); 67 var f = new Fibonacci(r.Next(20, 40), doneEvents[i]); 68 fibArray[i] = f; 69 ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i); 70 } 71 72 // Wait for all threads in pool to calculation... 73 WaitHandle.WaitAll(doneEvents); 74 Console.WriteLine("Calculations complete."); 75 76 // Display the results... 77 for (int i = 0; i < FibonacciCalculations; i++) 78 { 79 Fibonacci f = fibArray[i]; 80 Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN); 81 } 82 } 83 }