【发布时间】:2014-12-31 18:02:46
【问题描述】:
这里参考了 Jon Skeet 的文章 (http://csharpindepth.com/articles/general/singleton.aspx),第六版。
但是,我有一些私有变量,我想初始化一次,并被这个所谓的单例类中的方法使用。我在私有构造函数中初始化了它们,但很快发现,在多线程场景(Task.Run)中调用方法时它们为空。
在调试时,我观察到当我调用“实例”时,私有构造函数没有调用两次(应该是),所以我假设我的私有变量在那个时候不应该为空时间已经过去了(成功的“实例”调用)。
知道我应该如何声明、初始化和使用这些变量吗?
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
// my private variables
private readonly string _plantCode;
private Singleton()
{
var appSettings = ConfigurationManager.AppSettings;
string _plantCode = appSettings["PlantCode"] ?? "Not Found";
}
public SomeMethod()
{
var temp = _plantCode; // <== _plantCode becomes null here!
}
}
【问题讨论】:
标签: c# multithreading thread-safety singleton