Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Thread.CurrentThread.Join() make sense?

What is the effect of calling Thread.CurrentThread.Join(), and if/when would it make sense to call it?

like image 215
J. Andrew Laughlin Avatar asked Jun 12 '13 18:06

J. Andrew Laughlin


4 Answers

What is the effect of calling Thread.CurrentThread.Join()

You will block the execution of the current thread, and effectively dead lock it. It will cause the current thread to block until the current thread finishes, which will never happen.

, and if/when would it make sense to call it?

It really doesn't make sense to do this. You should never call this method in this manner.


On a side note, since you're using .NET 4, I would recommend avoiding using Thread.Join in general. Using the new Task/Task<T> classes is far nicer in many ways, as you can easily attach continuations (or always call Task.Wait() if you truly need to block).

like image 66
Reed Copsey Avatar answered Nov 16 '22 11:11

Reed Copsey


Was it really

CurrentThread.Join()

that you saw in real code - which I kind of doubt, unless it's some hack to prevent other threads to join on the current thread - or was it

CurrentThread.Join(someTimeout)

The latter is equivalent to

Thread.Sleep(someTimeout)

except that joining on the current thread allows message pumping to continue if you are in a GUI / COM situation.

like image 36
Evgeniy Berezovsky Avatar answered Nov 16 '22 12:11

Evgeniy Berezovsky


It actually make sense in world of observable. Lets say you have a queue listener in main and you want to keep main thread running forever. Instead of doing while(true) and put your code in the loop, last line you can write this. This way current thread will also be parent thread for other threads spawned within the application. Think of it as entry point for app.

like image 3
rohit Avatar answered Nov 16 '22 11:11

rohit


No, CurrentThread.Join() makes no sense
This could make your program stop running, making the thread A wait for thread A for example.

like image 2
Kauê Gimenes Avatar answered Nov 16 '22 10:11

Kauê Gimenes