[英]C# Singleton Thread-safe variables
我在这里引用了第六版的Jon Skeet的文章( http://csharpindepth.com/articles/general/singleton.aspx )。
但是,我有一些私有变量要初始化一次,并且可以由这个单例类中的方法使用。 我在私有构造函数中对其进行了初始化,但很快发现,在多线程方案( Task.Run )中,调用方法时它们为null。
调试时,我观察到当我调出“实例”时,私有构造函数不会被调用两次(应该是两次),因此我假设我的私有变量在该时间点不应该为null(后续的“实例”调用)。
关于如何声明,初始化和使用这些变量的任何想法?
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!
}
}
这就是问题:
string _plantCode = appSettings["PlantCode"] ?? "Not Found";
那不是分配给实例变量,而是声明一个新的局部变量。 您只想要:
_plantCode = appSettings["PlantCode"] ?? "Not Found";
(顺便说一句,这将在普通类中用相同的代码发生-与单例无关。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.