Hello everyone,
welcome back to can you spot the deadlock take 4. As a reminder, this a puzzle in a form of multithreaded code. You have to identify the issue that hides in it, usually a deadlock, but not always. Please post your answer in the comments section.
Since it has been a long time since the last episode, let’s start easy!
So what is the problem with this code and how would you fix it?
class Program { static void Main(string[] args) { var workerThread = new Thread(Worker); workerThread.Start(); workerThread.Join(); } static void Worker() { while (Thread.CurrentThread.IsAlive) { Console.Write("Blah "); } } }
My c# is rusty but i think you check .IsAlive before starting the thread so you’r going direct to exit 🙂
LikeLike
Hello
Well, you are onto something, but that is not it.
Thanks for your participation, and try again!
LikeLike
Too easy 🙂
IsAlive property is set to true when thread ends. In this case the thread will continue to run in background. Therefore the thread loop will never exit without an exception.
LikeLike
Too easy 😀
Thread property IsAlive is set to false only when the thread ends.
Or in this case thread doesn’t ends with main function and is still running in background.
the domain will not be unloaded without an exception.
LikeLike
Yes Abelman, you’re right. Well done!
Next question is : how to fix?
LikeLike
Stop the thread with a synchronization mechanism (Monitor, event, etc) and do not use IsAlive property to loop within a thread.
LikeLike