2

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

Sandepku
  • 861
  • 14
  • 31
  • 1
    Anything is only as thread safe as you make it; the standard, AFAIK, is that your static methods _*should*_ be thread safe. – Grant Thomas Jun 28 '13 at 13:12
  • @GrantThomas so I can assume, no thread is allowed to query a property of a class unless construction is complete? – Sandepku Jun 28 '13 at 13:14
  • 1
    Eric Lippert did a series on static constructors. Part 1 is at http://ericlippert.com/2013/02/06/static-constructors-part-one/. Well worth reading. And, yes, there is no lock needed in this case. – Jim Mischel Jun 28 '13 at 13:35

2 Answers2

3

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

Ahmed KRAIEM
  • 10,267
  • 4
  • 30
  • 33
  • so I can assume, no thread is allowed to query a property of a class unless construction is complete (may be by another thread)?? – Sandepku Jun 28 '13 at 13:15
  • i had a doubt whether the second thread waits for the construction to complete before the first thread comes out of Thread.Sleep , cheers – Sandepku Jun 28 '13 at 13:18
1

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.