Do properties have volatile effect?

后端 未结 6 2005
無奈伤痛
無奈伤痛 2021-02-19 10:54

In the code below will read1 be always equal to read2, provided property Flag can be changed from other threads? Concern here is that

6条回答
  •  轮回少年
    2021-02-19 11:24

    No, the property is not volatile.

    While I have not been able to obtain a satisfactory demonstration for your initial scenario, this alternative method should prove the statement nicely:

    class Program
    {
        public bool Flag { get; set; }
    
        public void VolatilityTest()
        {
            bool work = false;
            while (!Flag)
            {
                work = !work; // fake work simulation
            }
        }
    
        static void Main(string[] args)
        {
            Program p = new Program();
            var t = new Thread(p.VolatilityTest);
            t.Start();
            Thread.Sleep(1000);
            p.Flag = true;
            t.Join();
        }
    }
    

    Building this in Release mode will make the program deadlock, hence proving that Flag does not have volatile behavior (i.e. it gets "optimized" between reads).

    Replacing public bool Flag { get; set; } with public volatile bool Flag; will make the program terminate correctly.

提交回复
热议问题