Do properties have volatile effect?
c#, concurrency, multithreading
Solution
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.
Problem
In the code below will `read1` be always equal to `read2`, provided property `Flag` can be changed from other threads? Concern here is that `Flag` may get inlined. ``` private bool Flag {get; set;} public void MultithreadedMethod() { var read1 = Flag; /* some more code */ var read2 = Flag; } ``` UPD: Some other thread may change `Flag`'s value during `/* some more code */` execution. In this case `read1` should be different from `read2`. Will it always be the case? Won't inlining turn the property into an non-volatile field that will cause `read1` to be equal to `read2` despite tha fact `Flag` was changed between reads?