Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The point is: it might work, but it isn't <strong>guaranteed</strong> to work by the spec. What people are usually after is code that works for the right reasons, rather than working by a fluke combination of the compiler, the runtime and the JIT, which <em>might</em> change between framework versions, the physical CPU, the platform, and things like x86 vs x64.</p> <p>Understanding the memory model is a very very complex area, and I don't claim to be an expert; but people who <strong>are</strong> real experts in this area assure me that the behaviour you are seeing is not guaranteed.</p> <p>You can post as many working examples as you like, but unfortunately that doesn't prove much other than "it usually works". It certainly doesn't prove that it is <strong>guaranteed</strong> to work. It would only take a single counter-example to disprove, but finding it is the problem...</p> <p><s>No, I don't have one to hand.</s></p> <hr> <p>Update with repeatable counter-example:</p> <pre><code>using System.Threading; using System; static class BackgroundTaskDemo { // make this volatile to fix it private static bool stopping = false; static void Main() { new Thread(DoWork).Start(); Thread.Sleep(5000); stopping = true; Console.WriteLine("Main exit"); Console.ReadLine(); } static void DoWork() { int i = 0; while (!stopping) { i++; } Console.WriteLine("DoWork exit " + i); } } </code></pre> <p>Output:</p> <pre><code>Main exit </code></pre> <p>but still running, at full CPU; note that <code>stopping</code> has been set to <code>true</code> by this point. The <code>ReadLine</code> is so that the process doesn't terminate. The optimization seems to be dependent on the size of the code inside the loop (hence <code>i++</code>). It only works in "release" mode obviously. Add <code>volatile</code> and it all works fine.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload