namespace MyNameSpace
{
static class MyClass
{
static MyClass()
{
//Authentication process.. User needs to enter password
}
public static void MyMethod()
{
//Depends on successful completion of constructor
}
}
class Program
{
static void Main(string[] args)
{
MyClass.MyMethod();
}
}
}
Here is the sequence which I assumed
- Start of static constructor
- End of static constructor
- Start of main
- Start of MyMethod
- End of main
Now in any scenario if 4 will start before 2 I am screwed. Is it possible?
You only asked one question here but there are a dozen or so questions that you should have asked, so I’ll answer them all.
cctor)No. The correct sequence is:
The CLR is permitted to change the order in which static field initializers run in some cases. See Jon’s page on the subject for details:
The differences between static constructors and type initializers
Yes. If the cctor itself calls MyMethod then obviously MyMethod will be called before the cctor completes.
Yes. If the cctor uses another type whose cctor calls MyMethod then MyMethod will be called before the MyClass cctor completes.
No.
Yes. The cctor will finish on one thread before the static method can be called on any thread.
The cctor is guaranteed to be called at most once, no matter how many threads are involved. If two threads call MyMethod “at the same time” then they race. One of them loses the race and blocks until the MyClass cctor completes on the winning thread.
Really.
Then you have a classic lock order inversion condition. Your program deadlocks. Forever.
If it hurts when you do that then stop doing that. Never do something that can block in a cctor.
Neither are good ideas. My advice is that you should find a different way to ensure that the security-impacting preconditions of your methods are met.