我阅读了Jon Skeet关于如何实现C#单例模式的权威文章,并遵循以下模式。请注意,我的构造函数可能会执行一些工作,例如创建和填充字符串数组(或者它可能创建一些对象并将它们分配给私有变量等):
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应用服务器上运行类似的代码,日志中出现了空引用异常(不确定空引用是否与上述代码有关 - 我认为不是 - 日志中的调用堆栈并不有用)。