I am reading a Guid object twice, once within an if-statement, and once withing the block of the if-statement.
In C I would copy the variable locally, to make sure that the read operation inside the if-statement does not read a different value (if another thread changes this value inbetween).
I am skeptical that the following approach is a) thread safe and b) will give me the same value:
public class MyClass {
private Guid MyProp {get;set;} = Guid.Empty; //May be changed at will
public OnRunLoop() //Gets called periodicaly on a thread
{
var ALocalCopyOfTheProp = MyProp; //Copy locally
if(ALocalCopyOfTheProp == AValueFromAnotherPlace) //Read 1
{
...
var AnotherReadOfTheVariable = ALocalCopyOfTheProp; //Read 2
}
...
}
C#.NET natively has no copy capabilities from my googling, so what is best-practice in a case such as this?
Edit: - Note that in this case MyProp is out of my hands. I can not use a lock since the property is coming from elsewhere. (apologies for not making that clearer) - Guid is a struct and not a reference type