Search code examples
c#multithreading.net-corevolatile

Is volatile keyword useful with .net core under intel cpu?


I have tried few problematic cases where volatile helpful with .NET Framework. However under .NET Core I haven't found a single case that volatile is actually helping. Is memory model with .NET Core stronger than .NET Framework so that we don't need volatile any more ?

As an example the following code blocks indefinitely with .net framework if you build it with release mode but it doesn't with .net core. The reason is, in .net case the value is stored in a register and cached:

    class Program
    {
        static bool complete = false;
        static void Main()
        {

            var t = new Thread(() =>
            {
                bool toggle = false;
                while (!complete) toggle = !toggle;
            });
            t.Start();
            Thread.Sleep(1000);
            complete = true;
            t.Join();        // Blocks indefinitely
        }
    }

Solution

  • According to this article, volatile in C# tells the compiler / JIT to issue instructions that prevent instruction reordering. While the memory model of .NET on Intel platforms is normally strong enough that ordering would rarely happen, you never know on other platforms (for example ARM).

    In other words, there is rarely need to use volatile, unless you are afraid reordering can break your code. At the same time, when it comes to multi-threading, it is always best to be safe.