Everyone says static initializers are thread-safe, but I'm worried about a particular detail.
Let's say I have
static class MyStaticClass
{
public static readonly object myField = MyOtherClass.GetNewObject();
}
static class MyOtherClass
{
public static object GetNewObject()
{ /* arbitrary code that returns a new object */ }
}
Which of the following does C# guarantee, when MyStaticClass.myField is not yet initialized?
If threads 1 and 2 try to access
myFieldtogether (in that order),GetNewObjectwill have started executing before thread 2 readsmyField.If threads 1 and 2 try to access
myFieldtogether (in that order),GetNewObjectwill have finished executing before thread 2 readsmyField.
How about the CLR in general: if its guarantees differ from C#'s, in what ways do they differ?
Has the behavior changed in more recent versions of the .NET framework?
Note:
It's a tricky question, and I think a complete answer would probably mention the difference between a static constructor and a static initializer, and how they interact with beforefieldinit to produce the claimed result.