【问题标题】:C# Singleton Thread-safe variablesC# Singleton 线程安全变量
【发布时间】: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


    【解决方案1】:

    这就是问题所在:

    string _plantCode = appSettings["PlantCode"] ?? "Not Found";
    

    这不是分配给实例变量 - 它是声明一个新的 local 变量。你只想:

    _plantCode = appSettings["PlantCode"] ?? "Not Found";
    

    (顺便说一下,普通类中的相同代码也会发生这种情况 - 这与它是单例的事实无关。)

    【讨论】:

    • 呃……这是你在新年临近时仍在工作时所得到的。总之谢谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多