【发布时间】:2020-12-24 16:58:42
【问题描述】:
在下面的代码中,我有一个并发字典,用于存储单个键/值对,其中值是字符串的集合。
我将从不同的线程读取和更新这个单一键/值对中的字符串。
我知道,如果一个线程在另一个线程可能完成读取之前更改了一个值,那么并发字典并不是完全线程安全的。但同样我不确定字符串值是否真的进入这个话题,有人可以建议吗?
还值得一提的是,虽然我把这个“GetRunTimeVariables”方法放到了一个依赖注入的接口中,但由于应用程序启动和OIDC事件登录/退出的阶段,我实际上不能一直使用DI来访问这个方法。我需要访问不能使用依赖注入的类中的字典值,所以本质上我可以在应用程序的整个生命周期中根据需要从任何方式访问这个字典。
最后我不确定将这个方法推入接口是否有任何好处,另一个选项只是每次我需要它时都对这个类进行新的引用,对此的一些想法将不胜感激。
public class RunTimeSettings : IRunTimeSettings
{
// Create a new static instance of the RunTimeSettingsDictionary that is used for storing settings that are used for quick
// access during the life time of the application. Various other classes/threads will read/update the parameters.
public static readonly ConcurrentDictionary<int, RunTimeVariables> RunTimeSettingsDictionary = new ConcurrentDictionary<int, RunTimeVariables>();
public object GetRunTimeVariables()
{
dynamic settings = new RunTimeVariables();
if (RunTimeSettingsDictionary.TryGetValue(1, out RunTimeVariables runTimeVariables))
{
settings.Sitename = runTimeVariables.SiteName;
settings.Street = runTimeVariables.Street;
settings.City = runTimeVariables.City;
settings.Country = runTimeVariables.Country;
settings.PostCode = runTimeVariables.PostCode;
settings.Latitude = runTimeVariables.Latitude;
settings.Longitude = runTimeVariables.Longitude;
}
return settings;
}
}
字符串值的类:
public class RunTimeVariables
{
public bool InstalledLocationConfigured { get; set; }
public string SiteName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PostCode { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
【问题讨论】:
-
如果我没记错的话
TryGetValue不是线程安全的,但需要更多调查 (docs.microsoft.com/en-us/dotnet/api/…) -
人们会假设“尝试做某事”肯定比说“做某事”更安全,嗯,有兴趣了解更多信息。试图理解官方的 MS 文档很少有帮助
-
@ipinak ???一切都是线程安全的。唯一的问题是,如果您尝试执行
TryGetValue并且在失败时执行明确的Add。TryGetValue的结果只在被检索到的那一刻有效,不保证前一瞬间或后一瞬间有效。
标签: c# .net-core concurrentdictionary