views:

194

answers:

7

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.

+2  A: 

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)?

Jon Skeet
+4  A: 

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.

Ronald Wildenberg
A: 

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
}
Ion Todirel
Thank you all for your help. I used Threadcount and It solved my problem. I used do while loop: do { Console.WriteLine("Number of threads:{0}", ImageCompute.threadCount); } while (!(ImageCompute.threadCount == 0)); but, this is like counting number of threads. But do we have something like callback functions. Delegate which we can attach to each thread and triggers once it completes. Thanks again.
Harsha
This approach is prone to race conditions because incrementing and decrementing an integer is not an atomic operation (it involves a read and a write). Two threads could read the same value, decrement it and write it back, causing runningThreadsCount never to become 0.
Ronald Wildenberg
@Harsha If you want to do stuff like continuing work when threads are finished, take a look at the Task Parallel Library (check my answer).
Ronald Wildenberg
A: 

What about MyThread.ThreadState == System.Threading.ThreadState.Stopped ?

Marks
Patrick
A: 

You could use the ThreadPool class instead of an array, and use the 'GetAvailableThreads' method to check if all threads are available. See:

ThreadPool class.

Andrew
A: 

Have the threads call back to the class that you started them in to signal that they are done

Flunk
+1  A: 

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

Mike