I have created an array of threads and started all of them. How to know whether all threads have completed work. I don't want to use thread.wait or thread.join.
Well, you can test Thread.IsAlive
- but that will be out of date as soon as you've tested it, of course. You could keep a list of "currently alive" threads, and remove them one at a time when they stop, sleeping between test runs. For more detailed information you can use Thread.ThreadState
.
What's the bigger picture here? What are you trying to achieve, and why don't you want to call Thread.Join
(potentially with a timeout)?
If you are using .NET 4 you could use the Task Parallel Library and the ContinueWhenAll method.
You'd have to modify your threads to be represented as Task's. Tasks are easier to work with then threads. Usually you do not have to worry about lower-level things as you are forced to do now like scheduling or waiting for things to complete.
To what end? Diagnostics? Console.WriteLine.
If not, use a global variable (as in: accessible to all threads), increment it when when one of your threads starts, decrement when it finishes. If 0, all threads finished the work, but you must be careful to synchronize it correctly otherwise you'll get false positives. After you start you threads do a:
while (runningThreadsCount > 0)
{
// There are still working threads
}
What about MyThread.ThreadState == System.Threading.ThreadState.Stopped ?
You could use the ThreadPool class instead of an array, and use the 'GetAvailableThreads' method to check if all threads are available. See:
Have the threads call back to the class that you started them in to signal that they are done
if you want to intercept the work asynchronously you can use BackgroundWorkers all of which have a RunWorkerCompleted event and a Error and Cancelled properties in the event args
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx