问题描述
命名空间了myNameSpace
{
静态MyClass类
{
静态MyClass的()
{
//验证过程..用户需要输入密码
} 公共静态无效的MyMethod()
{
//取决于构造成功完成
}
} 类节目
{
静态无效的主要(字串[] args)
{
MyClass.MyMethod();
}
}
}
下面是我承担的序列
- 静态构造函数的开始
- 静态构造函数结束
- 主 开始
- 的MyMethod的开始
- 主 结束
现在在任何情况下,如果4将开始我拧2之前。这可能吗?
您只能在这里问一个问题,但也有你的十几问题应的问,所以我会回答他们所有
- Start of class constructor (also known as
cctor
) - End of cctor
- start of Main
- start of MyMethod
No. The correct sequence is:
- Start of cctor for Program, if there is one. There is not.
- End of cctor for Program, if there is one. There is not.
- Start of Main
- Start of cctor for MyClass
- End of cctor for MyClass
- Start of MyClass.MyMethod
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.
这篇关于如何做一个静态构造函数工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!