views:

163

answers:

4

Hi,

Thread.Join returns us if the thread has completed. The same we can determine using ThreadState. Then what is the difference between Thread.Join() and Thread.ThreadState?

Can we use them interchangeably?

+6  A: 

Thread.join WAITS for the thread to complete. ThreadState just gives you a snapshot of the thread and returns without waiting. There's also a variant of Thread.join that takes a time to wait. ThreadState and Join are extremely different and I don't think both can be used interchangeably.

Try doing a test where you do both calls on a thread that has an infinite loop.

SB
+12  A: 

The difference between Join and looking at ThreadState manually is that Join is a blocking operation. The function won't return until the timeout is reached or the target Thread completes. Checking the ThreadState is more of a peeking operation.

JaredPar
Correct me if I am wrong, but isn't ThreadState also unreliable?
Josh
Ahh... from *MSDN: There are two thread state enumerations, System.Threading.ThreadState and System.Diagnostics.ThreadState. The thread state enumerations are only of interest in a few debugging scenarios. Your code should never use thread state to synchronize the activities of threads.*http://msdn.microsoft.com/en-us/library/system.threading.threadstate.aspx
Josh
@Josh both are unreliable in the sense that they only provide information about the past :)
JaredPar
+2  A: 

When you call Thread.Join() it blocks the calling thread until the thread that has Join method is completed. If it is aborted, or successfully completed, Join() that follows will not block the calling thread. This allows you to have 10 worker threads and one main thread which operation must be run after all 10 threads completed. So you can call Join() on the first thread. That call will block the main thread until first working thread completes. After that you can call Join() on second thread, and so on until you get to thread #10. When you call Join() on it, and main thread gets resumed, you can be sure that all 10 threads completed and main thread can resume its operation.

For example:

Thread workers[] = new Thread[10];

//*** create and start threads ***

foreach(Thread worker in workers)
{
    worker.Join();
}

//All threads are completed, now this operation can continue...

On the other hand, Thread.ThreadState only returns the thread status (Aborted, Running, ...) without affecting the calling thread's state (not as Join which puts the calling thread in WaitSleepJoin state). So this is for use only if you want to check whats happening with thread so you can take a certain action, or you want to implement your own Join mechanism, and so on...

Cipi
A: 

Thread.Join will block the calling thread

Hiber