gpt4 book ai didi

c# - 使用 ConcurrentDictionary 作为缓存并处理更新

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:59 24 4
gpt4 key购买 nike

我有下面的代码,现在我想添加一个 UpdateSetting 方法。

我能看到的最好的方法是通过 ConcurrentDictionary 上的 TryUpdate 但这意味着知道以前的值,因此需要调用 GetSetting 这看起来有点恶心。你怎么看?有没有更好的办法?

注意:如果值不在缓存中,则什么都不做。成功更新缓存后,它应该调用 settingRepository.Update

谢谢

public class MySettings : IMySettings
{
private readonly ISettingRepository settingRepository;
private readonly ConcurrentDictionary<string, object> cachedValues = new ConcurrentDictionary<string, object>();


public MySettings(ISettingRepository settingRepository)
{
this.settingRepository = settingRepository;
}

public string GetSetting(string key)
{
return this.GetSetting<string>(key);
}

public T GetSetting<T>(string key)
{
object value;
if (!this.cachedValues.TryGetValue(key, out value))
{
value = this.GetValueFromRepository(key, typeof(T));
this.cachedValues.TryAdd(key, value);
}

return (T)value;
}

private object GetValueFromRepository(string key, Type type)
{
var stringValue = this.settingRepository.GetSetting(key);
if (stringValue == null)
{
throw new MissingSettingException(string.Format("A setting with the key '{0}' does not exist.", key));
}

if (type == typeof(string))
{
return stringValue;
}

return ConvertValue(stringValue, type);
}

private static object ConvertValue(string stringValue, Type type)
{
return TypeDescriptor.GetConverter(type).ConvertFromString(stringValue);
}

}

最佳答案

可能值得获取现有值以避免更新存储库。如果比尝试更昂贵,则异常(exception)

public bool UpdateSetting<T>(string key, T value)
{
lock
{
T oldValue;
if (this.cachedValues.TryGetValue(key, out oldValue)
{
if (oldValue != value)
{
this.cachedValues[key] = value;
settingRepository.Update(key, value);
}
return true;
}
else
{
return false;
}
}
}

关于c# - 使用 ConcurrentDictionary 作为缓存并处理更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28116318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com