I am getting the “a reference to a volatile field will not be treated as volatile” warning in an application. I understand why.
As a simple example will the below code make the issue thread safe even though I will get the warning still?
private volatile int myVal = 10;
private int myNonVolatileNumber = 50;
private static readonly object lockObject = new object();
private void ChangeValue(ref int Value)
{
lock (lockObject)
{
Value = 0;
}
}
private void MyMethod()
{
ChangeValue(ref myVal); //Warning here
ChangeValue(ref myNonVolatileNumber); //no warning
}
Locking forces memory barriers on both sides, so yes, your example is thread safe.