Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constructors are guaranteed to be run only once per application domain.How?

Static constructors are guaranteed to be run only once per application domain. It is called automatically before the first instance is created or any static members are referenced. How does the CLR guarantee this?
Suppose there are two threads visit a class which has a static constructor simultaneously. And both these two threads are at very first time. As below:

class SomeType
{
    Static SomeType()
    {
      Console.Write("hello");
    }
}

So because of the simultaneity, how does the CLR guarantee console write only once? Use the Lock or other things??

like image 634
roast_soul Avatar asked Jun 13 '14 05:06

roast_soul


People also ask

Can we have multiple static constructor?

A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.

How many times static constructor gets executed in a class?

Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.

Which statement is true about static constructor?

10. Which among the following is true for static constructor? Explanation: Static constructors can't be parameterized constructors. Those are used to initialize the value of static members only.

How does static constructor private constructor work?

Static constructor is called before the first instance of class is created, wheras private constructor is called after the first instance of class is created. 2. Static constructor will be executed only once, whereas private constructor is executed everytime, whenever it is called.


1 Answers

The CLR takes out a lock before entering into a static constructor to guarantee it is only executed once by a single thread.

This makes it easy to deadlock your application if you go creating threads within the static constructor.

See this MSDN blog post for an example. Basically though, this deadlocks:

using System.Threading;
class MyClass
{
    static void Main() { /* Won't run... the static constructor deadlocks */  }

    static MyClass()
    {
        Thread thread = new Thread(arg => { });
        thread.Start();
        thread.Join();
    }
}
like image 57
Simon Whitehead Avatar answered Sep 27 '22 03:09

Simon Whitehead