Skip to main content
Journey Uncommon Logo
JourneyUncommon
hardC#volatile and memory barriersSingle-choice MCQ

A field is written by one thread and read in a spin loop by another. The reading thread never exits the loop in a Release build, but works in Debug. Setting the field `volatile` fixes it. At the IL/JIT level, what is the precise mechanism by which the bug occurred and `volatile` cured it?

private bool _stop; // make volatile to fix public void Run() { while (!_stop) { } } public void Stop() => _stop = true;