C # - Static strings in readonly - can you run into multi-threaded problems?

public class MyClass<T>
{
    public static readonly String MyStringValue;

    static MyClass()
    {
        MyStringValue = GenerateString();
    }

    private static String GenerateString()
    {
        //Dynamically generated ONCE per type (hence, not const)
    }

    public void Foo()
    {
        Console.WriteLine(MyStringValue);
    }
}

I understand that a static readonly String will not be generated until a static constructor is called in the class. But the static constructor will not be called until one of the static methods or variables is available.

In a multi-threaded environment, is it possible to run into problems because of this? Basically, the default static constructor for singleton is locked, or do I need to do this myself? That is ... I have to do the following:

private static Object MyLock;

static MyClass()
{
    lock(MyLock)
    {
        if (MyStringValue == null)
            MyStringValue = GenerateString();
    }
}
+5
source share
2 answers

. .

, . .

+8

, get accessor, , ? get .

+1

All Articles