今天有小伙伴在评估某类线程安全问题的时候,怀疑到静态构造函数里面去了。于是就有了本文。
@TOC
静态构造函数的执行时机
根据官方文档 Static Constructors - C# Programming Guide 所述:
A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. A static constructor will run before an instance constructor. A type's static constructor is called when a static method assigned to an event or a delegate is invoked and not when it is assigned. If static field variable initializers are present in the class of the static constructor, they will be executed in the textual order in which they appear in the class declaration immediately prior to the execution of the static constructor.
静态构造函数的线程安全
参考资料
- Are static constructors thread-safe? · Issue #10243 · dotnet/docs
- Classes - C# language specification - Microsoft Docs
- static constructor and thred safety
- Thread Safety In C#
- multithreading - Is the C# static constructor thread safe? - Stack Overflow
- Static Constructors - C# Programming Guide - Microsoft Docs
我的博客会首发于 https://blog.walterlv.com/,而 CSDN 会从其中精选发布,但是一旦发布了就很少更新。
如果在博客看到有任何不懂的内容,欢迎交流。我搭建了 dotnet 职业技术学院 欢迎大家加入。
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名吕毅(包含链接:https://walterlv.blog.csdn.net/),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系。