[英]C# Singleton Thread-safe variables
I have referred to Jon Skeet's article here ( http://csharpindepth.com/articles/general/singleton.aspx ), the sixth version. 我在这里引用了第六版的Jon Skeet的文章( http://csharpindepth.com/articles/general/singleton.aspx )。
However, I have some private variables that I want initialized once, and be used by methods in this supposedly singleton class. 但是,我有一些私有变量要初始化一次,并且可以由这个单例类中的方法使用。 I initialized them in the private constructor, but soon found out, that they are null when invoking the methods, in a multi-threaded scenario ( Task.Run ).
我在私有构造函数中对其进行了初始化,但很快发现,在多线程方案( Task.Run )中,调用方法时它们为null。
When debugging, I observed that the private constructor doesn't called twice (which should be) when I call out for an "Instance", and so I assume that my private variables, shouldn't be null at that point in time already (succeeding "Instance" calls). 调试时,我观察到当我调出“实例”时,私有构造函数不会被调用两次(应该是两次),因此我假设我的私有变量在该时间点不应该为null(后续的“实例”调用)。
Any idea on how should I declare, initialize, and use these variables? 关于如何声明,初始化和使用这些变量的任何想法?
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!
}
}
This is the problem: 这就是问题:
string _plantCode = appSettings["PlantCode"] ?? "Not Found";
That isn't assigning to the instance variable - it's declaring a new local variable. 那不是分配给实例变量,而是声明一个新的局部变量。 You just want:
您只想要:
_plantCode = appSettings["PlantCode"] ?? "Not Found";
(This would happen with the same code in a normal class, by the way - it has nothing to do with the fact that it's a singleton.) (顺便说一句,这将在普通类中用相同的代码发生-与单例无关。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.