01 Jan 2015 by K Bonneau

If you haven't yet, check out the the first part: Part 1

1. Different Threads, Different Values

What is the output of the below snippet in Release mode? Is it any different when you compile it in Debug mode?

So if you did run it in release mode, you would get The process is either hung or did not complete within the allocated time.

Now go ahead and uncheck "Release Mode" (at the top of the snippet) and run it again. It should say complete!

In Debug mode it works as expected. When we set isComplete = true after half a second, the thread which is continuously checking for this variable sees that and exits.

In Release mode however, the isComplete variable is cached in a cpu register, and the thread keeps checking the stale value, even when the main thread changes it to true.

2. Static Constructors First

Everyone says static constructors get called first, and then the instance constructors. If you want to prove them wrong, show them the above snippet.

3. Deadlock With No Locks

Ok, so the title was a spoiler. This snippet would result in a deadlock and the snippet compiler would output The process is either hung or did not complete within the allocated time. The runtime guarantees that each type is initialized only once. This also means that it guarantees that a Static constructor can only be run once. How does it achieve this? Using locks!



If you have any interesting c# snippets that you would like to include, please share those in the comments below.

More Challenges: Predict the Output Challenge (C#) - Part 3