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??
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.
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.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With