When compiling from C# to IL, the optimization removing the check from RunHelper
will not happen.
However, the JIT (that compiles from IL to machine code) could take RunHelper
and inline a copy inside of Run
to void the call, and then the optimization you fear can heppen. No, reflection does not prevent this, because you will only see the IL with reflection, but not the machine code.
However, even if that optimization does not happen, you need to worry about thread visibility. If the system uses this code relatively often, it will keep terminate
in cache, and - depending on the CPU architecture※ - other threads may not be aware of changes made to it. This is why you should use volatile
(or similar solution).
※: On a computer with a single hardware thread (single core, and no hyper-threading or similar technology) there is no problem. If there are multiple hardware threads, they all have a cache, and there may or may not be shared caches. In those cases, you risk the changes to the value being invisible virtually forever.
There are some other caveats with volatile that - as far as I can tell - do not affect your code.
For instance, reordering does not only happen in the compiler. Reorders can also happen in the CPU, that is, the CPU may not execute the machine code strictly in the order it recieve them (see Out-of-order execution). The use volatile
puts contraints on that reordering. However, writes could still be moved after reads (see: Threading in C# - PART 4: ADVANCED THREADING). You will be needing full memory barrier to fix it (Interlocked.MemoryBarrier()
in .NET Core and Thread.MemoryBarrier()
otherwise).
And, of course, there is the ABA problem. If you face it, you would need Interlocked
to solve it, which also means you cannot use volatile
and will have to only use Interlocked
or volatile operations (Volatile.Read
/Volatile.Write
in .NET Core or Thread.VolatileRead
/Thread.VolatileWrite
otherwise) to work with the variable, forcing you to change from bool
to int
, because Interlocked
does not work with bool
.
See also: