Hi all, I have written some code that invokes a method a few hundred times
and then it immediately finishes.
I would like it to instead:
1. start the hundreds of threads (asynchronously)
2. Then block until all threads have finished executing
Currently I have something like the following:
--------------
MyClass myObj = new MyClass(initVar);
for (int i = start; i <= finish; i++)
{
try
{
object iAsObj = (object) i;
ThreadPool.QueueUserWorkItem(new WaitCallback(myObj.doTask), iAsObj);
}
catch (Exception ex)
{
m_textBox.AppendText("An error occurred");
}
}
//would like to block here until all of the above threads have finished
//I was hoping ThreadPool would have a method that I could block on
-----------------------
I would like to just check to see if there are any active threads in the
thread pool and/or if there are any threads in the queue to become active.
But the ThreadPool class doesn't seem to have any way of determining if all
threads have finished executing.
The only workaround I could think of is to put a static variable in MyClass,
and increment it as I enter the doTask method and then decrement it right
before I leave the method - but this is definitely a hack. Mostly because if
I pushed this into a multi-processor environment there would be a chance that
multiple threads would attempt to change that variable at the same time -
i.e. making it a volatile variable.
Is there another way to manage my threads? Is the only other alternative to
use BeginInvoke?
Thanks,
Novice