Stream Security for Static Initializers in C #

Everyone says that static initializers are thread safe, but I'm worried about the specific details.

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 */ } } 

Which of the following conditions guarantees C # when MyStaticClass.myField is not yet initialized?

  • If threads 1 and 2 try to access myField together (in that order), GetNewObject will execute the initial one before thread 2 reads myField .

  • If threads 1 and 2 try to access myField together (in that order), GetNewObject will complete before thread 2 reads myField .

How about the CLR as a whole: if its guarantees are different from C #, how do they differ?
Is the behavior changed in later versions of the .NET Framework?

Note:

This is a tricky question, and I think the complete answer will probably mention the difference between the static constructor and the static initializer and how they interact with beforefieldinit to get the stated result.

+4
source share
2 answers

Case 2 will be completed. A field, property, or method of a class cannot be dereferenced until the type is initialized and the type is initialized until the static constructor completes. The static constructor, as far as I know, is a blocking call.

http://msdn.microsoft.com/en-us/library/aa645612(v=vs.71).aspx

"The static constructor for the class runs no more than once in the specified application domain.

See this answer from Eric Lippert: fooobar.com/questions/71516 / ... and note that "cctor" is the IL for the static constructor.

No clickers call MyMethod directly or indirectly! Can I now call a static method, such as MyMethod, before it finishes working with the MyClass instructor?

No.

Is this true even if multiple threads are involved?

Yes. The coctor will terminate on a single thread before the static method can be called on any thread.

Is it possible to call cctor more than once? Suppose two threads make cctor work.

It is guaranteed that cctor will be called no more than 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 circuit finishes on the winning thread.

+3
source

Taken from MSDN :

Static elements are initialized before the static member is available for the first time and before the static constructor is called, if any.

If the second method runs in two different threads, but never uses a static class, it will never be created. However, if there is a link to it, it will be initialized before either of the two threads gets access to it.

+2
source

Source: https://habr.com/ru/post/1488375/


All Articles