65.9K
CodeProject is changing. Read more.
Home

Working with ThreadPool

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Nov 3, 2011

CPOL
viewsIcon

28242

A workaround for using more than 64 threads with ThreadPool and WaitHandle class.

Before going further, please check the MSDN link How to: Use a Thread Pool [^]. The above link will give you an idea on how to use Thread Pool.

Now in code given at the above link, in Main() method if you make a small change as given below:

const int FibonacciCalculations = 100; //Change its value to 100 from 10
The program will throw a NotSupportedException.

This is because a program can pass only 64 handles to WaitHandle class. So if you want to work with more than 64 threads simultaneously, this program won't work.

I worked out the above program to fulfill my requirement of creating more threads. I made few changes only in the Main() method. Take a look:

static void Main()
        {
            const int FibonacciCalculations = 100;

            // One event is used for each Fibonacci object
            List<ManualResetEvent> doneEvents = null;
            Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
            Random r = new Random();
            int totalCount = 0;
            // Configure and launch threads using ThreadPool:
            Console.WriteLine("launching {0} tasks...", FibonacciCalculations);

        ProcessThread://Label
            doneEvents = new List<ManualResetEvent>();
            for (int i = totalCount, j = 0; i < FibonacciCalculations && j < 64; i++, j++)
            {
                totalCount++;

                doneEvents.Add(new ManualResetEvent(false));
                Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[j]);
                fibArray[i] = f;
                ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
            }

            // Wait for all threads in pool to calculation...
            WaitHandle.WaitAll(doneEvents.ToArray());            

            if (totalCount < FibonacciCalculations)
                goto ProcessThread;

            Console.WriteLine("All calculations are complete.");
            // Display the results...
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                Fibonacci f = fibArray[i];
                Console.WriteLine("Result {2} : Fibonacci({0}) = {1}", f.N, f.FibOfN, i);
            }
        }
Now run the program and it will work fine for 100 threads. In this manner, you can work with more than 64 threads.

I have used this method to achieve my goal, but if anyone else has a better way to achieve this, please share it with us.

Note: ManualResetEvent closing tag seen at the end of the code snippet is not part of the code snippet. I am not been able to remove those closing tags.

Thanks, Nagendra.