Is this code thread safe?
public class SomeType
{
public int i {get;} = 5;
public string s {get;} = "Asdf";
public double d {get;} = 1.5;
}
public class SomeClass
{
public static SomeType SomeProp { get; } = new SomeType();
}
public static async Task Main()
{
await Task.WhenAll(
Task.Run(() => { _ = SomeClass.SomeProp; }),
Task.Run(() => { _ = SomeClass.SomeProp; })
);
}
I am concerned about the concurrent read from SomeClass.SomeProp
.
It seems to be thread safe since - AFAIK - just reading is always thread safe.
But - again AFAIK - properties are lazily initialized so the first read from SomeProp
will actually write new SomeType()
to it? So if SomeProp
has never been read from and then two threads try to concurrently read from it for the first time then we have a concurrent write and a data race?
Is this the case? If so, then how to make it thread safe (and do I have to protect the read with a full-blown lock
?)