Pergunta

I have a sample static class

public static class SampleClass
   {
    private static readonly string _personName;
    private static readonly string _country;

    static SampleClass()
    {
        _personName = "JourneyMan";
        _country = "Zee";
        System.Threading.Thread.Sleep(5000);
    }

    public static string PersonName
    {
        get { return _personName; }
    }

    public static string Country
    {
        get { return _country; }
    }
}

I have deliberately introduced a Thread.Sleep in the static constructor.

I wrote a sample application in which two threads wait on a ManualResetEvent. I tried to simulate the scenario where one thread tries to query a property and is executing the static constructor and is put to sleep, can the other thread access the second property and return null value?

But according to what I observed, the second thread cannot fetch the property value unless the construction is complete.

Is this handled for us? or am I doing something wrong?

So can I assume, in the above case, there is no lock needed to ensure construction of static class is complete?

Thanks

Foi útil?

Solução 2

You should be thread safe in this example. Based on the Static Constructors documentation a static constructor 'is called automatically before the first instance is created or any static members are referenced', so it should be impossible to reference the members before the constructor has completed.

Outras dicas

The static constructor is thread safe, static properties no.

Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. http://msdn.microsoft.com/en-us/library/aa645612.aspx

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top