Reputation: 924
Thread.Join and waitHandle.WaitOne(), both of them force the calling thread to wait. Until the thread has finished executing and until the waitHandle.Set() is called respectively.
But is there any difference between the 2 besides this?
Upvotes: 1
Views: 2204
Reputation: 1089
@helloworld, A distinction is "at the end of the method". Unless your method catches all exceptions, it may exit due to unhandled exception (e.g. due to thread.abort), before your call to WaitHandle.Set().
WaitHandles require cooperation/knowledge between threads. The called thread has to be passed the wait handle, and it has to signal at the appropriate time. It is useful, when two threads are sharing a resource such as a pub-sub queue.
WaitHandles are just one of many signaling/locking mechanisms. Semaphores, mutexes, lock files and even thread-shared variables (accessed carefully, e.g. Interlocked.Increment) can be used for signaling.
Thread.Join - does not require any cooperation from the called thread. When the called thread is done for any reason, including abnormal termination, join returns.
Thread.Join is more like Process.Wait. Process.Wait returns when the process terminates for any reason.
In short, if you need to know when a thread terminates for any reason, use Thread.Join.
When you need to know if a thread has executed to a certain point, use signaling.
Upvotes: 1
Reputation: 73492
...both of them force the calling thread to wait until the called thread has finished executing.
No, they don't. They are completely different.
WaitHandle.WaitOne will block the calling thread until the wait handle is signaled.
Thread.Join will block the calling thread until the thread object which the Join
method is called is finished executing(terminated)
Upvotes: 6