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