单例 属性 在 "OnClicked" 事件期间未更新

Singleton property not updating during "OnClicked" event

我确定我记得这是一个线程问题,但我找不到答案。看起来应该很简单。我有以下代码:

    private void Dingle_Clicked(object sender, RoutedEventArgs e)
    {
        dynamic doc = ScraperBrowser.Document;
        string htmlText = doc.documentElement.InnerHtml;
        htmlText = htmlText.Replace("\r\n", " ");

        Regex targetStart = new Regex(this works just fine);
        MatchCollection target = targetStart.Matches(htmlText);

        string priceData = target[0].Value; 

        foreach (StorePriceData spData in Lists.Singleton.MedicineList[medIndex].Prices)
        {
            Regex rx = new Regex(spData.StoreName + @".+?($\d+\.\d+)");
            MatchCollection matches = rx.Matches(priceData);
            if (matches.Count > 0)
            {
                if (matches[0].Groups.Count > 0)
                {
                    spData.MedicinePrice = matches[0].Groups[1].Value;
                }
            }
        }

        string cookie = Application.GetCookie(new Uri("https://www.goodrx.com"));
        ++medIndex;
        ScraperBrowser.Navigate(Lists.Singleton.MedicineList[medIndex].GoodRxUrlString);
    }

我遇到的问题是 spData.MedicinePrice 获取了值,但单例“MedicineList”中的值未更新。我怎样才能更新这个值?

单例代码:

public class Lists
{
    private static Lists _singleton;
    public static Lists Singleton
    {
        get
        {
            if (_singleton == null) _singleton = new Lists(); return _singleton;
        }
    }

    public List<MedicineInfo> MedicineList {
        get
        {
            return new List<MedicineInfo>()
            {
                new MedicineInfo() { Name = "ZOLPIDEM TAB 10MG", Doses = "30 tablets" },
                new MedicineInfo() { Name = "PANTOPRAZOLE TAB 40MG", Doses = "30 tablets" }
            };
        }
    }
}

MedicineInfo class 代码:

public class MedicineInfo
{
    public MedicineInfo()
    {
        Prices = new List<StorePriceData>()
        {
            new StorePriceData() { StoreName = "xxxx" },
            new StorePriceData() { StoreName = "yyyy" },
            new StorePriceData() { StoreName = "zzzz" },
        };
    }

    public string Name { get; set; }
    public string Doses { get; set; }
    public List<StorePriceData> Prices { get; set; }
}

谢谢!

卡尔

每次调用 MedicineList 的 getter 时,您都会返回一个新的 List<MedicineInfo>

此外,Lists并不是真正的单例。更好的实现应该是这样的:

public sealed class Lists
{
    private static readonly Lists _singleton = new Lists();

    private readonly List<MedicineInfo> _medicineList = new List<MedicineInfo>
    {
        new MedicineInfo() { Name = "ZOLPIDEM TAB 10MG", Doses = "30 tablets" },
        new MedicineInfo() { Name = "PANTOPRAZOLE TAB 40MG", Doses = "30 tablets" }
    };


    private Lists() { }

    public static Lists Singleton => _singleton;

    public List<MedicineInfo> MedicineList => _medicineList;
}