In place of manually creating an array of threads that do similar work you can also use the C# Threadpool methods to handle threads. You typically make use of them in server applications or generally in worker threads that do routine work in the background.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | using System; using System.Threading; namespace ThreadPool { public class WorkerClass { private ManualResetEvent cDoneEvent; private int cThreadID; private int cSleep; public WorkerClass(int pThreadID, ManualResetEvent pDoneEvent) { cThreadID = pThreadID; cDoneEvent = pDoneEvent; Random lRand = new Random(); for (int i = 0; i < pThreadID; i++) cSleep = lRand.Next(1, 8) * 1000; Console.WriteLine("WorkerClass() : {0} {1}", cThreadID, cSleep); } public int getSleep() { return(cSleep); } public int getThreadID() { return (cThreadID); } /* * Callback method called by the thread pool * */ public void ThreadPoolCallback(Object threadContext) { Console.WriteLine("Thread {0} : Entry point called.", cThreadID); Thread.Sleep(cSleep); Console.WriteLine("Thread {0} : End of callback method reached.", cThreadID); cDoneEvent.Set(); } } /* * * */ class Program { static void Main(string[] args) { const int lNumWorkers = 5; ManualResetEvent[] lEventsDone = new ManualResetEvent[lNumWorkers]; WorkerClass[] lWorkers = new WorkerClass[lNumWorkers]; // Configure and launch threads using ThreadPool: Console.WriteLine("launching {0} tasks...", lNumWorkers); for (int i = 0; i < lNumWorkers; i++) { lEventsDone[i] = new ManualResetEvent(false); lWorkers[i] = new WorkerClass(i, lEventsDone[i]); System.Threading.ThreadPool.QueueUserWorkItem(lWorkers[i].ThreadPoolCallback, i); } // for (int i =... // Wait for all threads in pool WaitHandle.WaitAll(lEventsDone); Console.WriteLine("All Threads returned"); // Display the results... for (int i = 0; i < lNumWorkers; i++) Console.WriteLine("Thread {0} was sleeping for {1} seconds", lWorkers[i].getThreadID(), lWorkers[i].getSleep()); } } } |