每个人都说静态初始化程序是线程安全的,但我担心一个特定的细节。
比方说我有
static class MyStaticClass { public static readonly object myField = MyOtherClass.GetNewObject(); } static class MyOtherClass { public static object GetNewObject() { /* arbitrary code that returns a new object */ } }注意:
这是一个棘手的问题,我认为完整的答案可能会提到静态构造函数和静态初始化程序之间的区别,以及它们如何与beforefieldinit交互以产生声明的结果。
Everyone says static initializers are thread-safe, but I'm worried about a particular detail.
Let's say I have
static class MyStaticClass { public static readonly object myField = MyOtherClass.GetNewObject(); } static class MyOtherClass { public static object GetNewObject() { /* arbitrary code that returns a new object */ } }Note:
It's a tricky question, and I think a complete answer would probably mention the difference between a static constructor and a static initializer, and how they interact with beforefieldinit to produce the claimed result.
最满意答案
案例2将受到尊重。 在初始化类型之前,不能取消引用类字段,属性或方法,并且在静态构造函数完成之前不会初始化类型。 因此,就我而言,静态构造函数是一个阻塞调用。
http://msdn.microsoft.com/en-us/library/aa645612(v=vs.71).aspx
“类的静态构造函数在给定的应用程序域中最多执行一次。”
请参阅Eric Lippert的回复: https ://stackoverflow.com/a/9399027/2420979并注意“cctor”是静态构造函数的IL。
没有cctors直接或间接地调用MyMethod! 现在有可能在MyClass的cctor完成之前调用像MyMethod这样的静态方法吗?
没有。
即使涉及多个线程,这仍然是正确的吗?
是。 在任何线程上调用静态方法之前,cctor将在一个线程上完成。
可以不止一次调用cctor吗? 假设两个线程都导致cctor运行。
无论涉及多少线程,都保证最多只调用一次cctor。 如果两个线程“同时”调用MyMethod,那么它们就会竞争。 其中一个失败了比赛并阻塞,直到MyClass cctor在获胜线程上完成。
Case 2 will be honoured. A class field, property, or method cannot be dereferenced until the type has been initialized, and the type will not be initialized until the static constructor is completed. The static constructor is, to the best of my knowledge, therefore a blocking call.
http://msdn.microsoft.com/en-us/library/aa645612(v=vs.71).aspx
"The static constructor for a class executes at most once in a given application domain."
See this reply from Eric Lippert: https://stackoverflow.com/a/9399027/2420979 and note that "cctor" is IL for static constructor.
No cctors call MyMethod, directly or indirectly! Now is it ever possible for a static method like MyMethod to be called before the cctor of MyClass completes?
No.
Is that still true even if there are multiple threads involved?
Yes. The cctor will finish on one thread before the static method can be called on any thread.
Can the cctor be called more than once? Suppose two threads both cause the cctor to be run.
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.
更多推荐
发布评论