【发布时间】:2014-10-15 17:17:18
【问题描述】:
我阅读了 Jon Skeet 关于如何实现 C# 单例的权威 post 并遵循以下模式。请注意,我没有空的 ctor。我的 Ctor 可能会做一些工作,例如创建和填充字符串数组(或者它可能会创建一些对象并将它们分配给私有变量等):
public class MyClass
{
/// <summary>
/// Get singleton instance of this class.
/// </summary>
public static readonly MyClass Instance = new MyClass();
/// <summary>
/// a collection of strings.
/// </summary>
private string[] strings;
private MyClass()
{
this.strings = new string[]
{
"a",
"b",
"c",
"d",
"e"
};
}
public void MyMethod()
{
// tries to use this.strings.
// can a null ref exception happen here when running multithreaded code?
}
}
是否高于线程安全?我之所以问,是因为我在 asp.net appserver 上运行了类似的代码,并在日志中获取了 null ref 异常(不确定 null ref 是否与上述相关 - 我认为不是 - 并且日志中的调用堆栈没有帮助)。
【问题讨论】:
-
Yes, the initialization is thread-safe。它保证只发生一次,并且只会实例化您的类的一个实例。
-
是的,它是线程安全的。一个额外的信息 - 如果你想要单例“每个线程”,你可以用 ThreadStatic 属性标记静态字段。
标签: c# thread-safety