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;
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;
List<ManualResetEvent> doneEvents = null;
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();
int totalCount = 0;
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
ProcessThread:
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);
}
WaitHandle.WaitAll(doneEvents.ToArray());
if (totalCount < FibonacciCalculations)
goto ProcessThread;
Console.WriteLine("All calculations are complete.");
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.