C#Singleton线程安全变量

alp*_*ler 0 c# singleton multithreading thread-safety

我在这里提到了Jon Skeet的文章(http://csharpindepth.com/articles/general/singleton.aspx),第六个版本.

但是,我有一些私有变量,我想初始化一次,并被这个所谓的单例类中的方法使用.我在私有构造函数中初始化它们,但很快发现,在多线程场景(Task.Run)中调用方法时它们是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!
    }

}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

这就是问题:

string _plantCode = appSettings["PlantCode"] ?? "Not Found";
Run Code Online (Sandbox Code Playgroud)

那不是分配给实例变量 - 它声明了一个新的局部变量.你只想要:

_plantCode = appSettings["PlantCode"] ?? "Not Found";
Run Code Online (Sandbox Code Playgroud)

(顺便说一下,这会发生在普通类中的相同代码中 - 它与单例的事实无关.)