问题描述
如果一个人创建这样一个只读的静态成员:
If one creates a readonly static member like this:
public sealed class MyClass
{
public readonly static MyClass Instance = new MyClass();
}
我们知道,静态构造函数将初始化MyClass.Instance场,如果一些线程访问MyClass的拳头时间。但是,将单个实例(在此情况下MyClass的)被创建如果多个线程都在同一时间访问MyClass的(即是静磁场线程安全的初始化)
We know that the static constructor will initialise the MyClass.Instance field if some thread accesses MyClass the fist time. But, will a single instance (in this case MyClass) be created if multiple threads all accesses MyClass at the same time (i.e. is the initialisation of the static field thread-safe)?
推荐答案
.NET CLR保证了静态初始化始终是线程安全的。不管有多少线程访问它和什么样的顺序,它都会被初始化一次。
.NET CLR ensures that static initialization is always thread-safe. No matter how many threads are accessing it and what order, it will always be initialized once.
您的代码似乎显示出Singleton模式的开始的迹象。
基本上,如果你想你初始化类之前运行自定义代码,那么你需要确保你自己了。结果
线程安全的,你需要让你的自定义代码线程安全的一个例子。但静态初始化部分始终是线程安全的。
Your code seems to show signs of the beginnings of a Singleton pattern.
Basically if you want to run custom code before you initialize the class, then you need to ensure thread-safety on your own.
This is an example where you would need to make your custom code thread safe. But the static initialization part is always thread safe.
这篇关于在只读静态字段初始化线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!