In the code below will read1 be always equal to read2, provided property Flag can be changed from other threads? Concern here is that
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.