コード例 #1
0
        static void Main34()
        {
            const int TaskCount = 10;

            // One event is used for each Fibonacci object
            ManualResetEvent[] doneEvents = new ManualResetEvent[TaskCount];
            OneCalc[]          fibArray   = new OneCalc[TaskCount];
            Random             r          = new Random();

            // Configure and launch threads using ThreadPool:
            Console.WriteLine("launching {0} tasks...", TaskCount);
            for (int i = 0; i < TaskCount; i++)
            {
                doneEvents[i] = new ManualResetEvent(false);
                OneCalc f = new OneCalc(r.Next(20, 40), doneEvents[i]);
                fibArray[i] = f;
                ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
            }

            // Wait for all threads in pool to calculation...
            WaitHandle.WaitAll(doneEvents);
            Console.WriteLine("All calculations are complete.");
            Console.ReadKey();

            // Display the results...
            for (int i = 0; i < TaskCount; i++)
            {
                OneCalc f = fibArray[i];
                Console.WriteLine("OneCalc({0}) = {1}", f.N, f.FibOfN);
            }
        }
コード例 #2
0
        static void Main34()
        {
            const int TaskCount = 10;

            // One event is used for each Fibonacci object
            ManualResetEvent[] doneEvents = new ManualResetEvent[TaskCount];
            OneCalc[] fibArray = new OneCalc[TaskCount];
            Random r = new Random();

            // Configure and launch threads using ThreadPool:
            Console.WriteLine("launching {0} tasks...", TaskCount);
            for (int i = 0; i < TaskCount; i++)
            {
                doneEvents[i] = new ManualResetEvent(false);
                OneCalc f = new OneCalc(r.Next(20, 40), doneEvents[i]);
                fibArray[i] = f;
                ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
            }

            // Wait for all threads in pool to calculation...
            WaitHandle.WaitAll(doneEvents);
            Console.WriteLine("All calculations are complete.");
            Console.ReadKey();

            // Display the results...
            for (int i = 0; i < TaskCount; i++)
            {
                OneCalc f = fibArray[i];
                Console.WriteLine("OneCalc({0}) = {1}", f.N, f.FibOfN);
            }
        }