c# - C#中的通用缓存

标签 c# generics caching

是否有更有效的方法来检查缓存数据是否存在,是否确实获取了它,以及是否没有调用 api/数据库然后缓存它?一遍又一遍地编写这样的代码对我来说似乎效率很低。

List<Map> maps = new List<Map>();
List<Playlist> playlists = new List<Playlist>();

if (SingletonCacheManager.Instance.Get<List<Map>>("Maps") != null)
{
    maps = SingletonCacheManager.Instance.Get<ListMap>>("Maps");
}
else
{
    maps = _mapRepository.FindBy(x => x.Active).ToList();
    SingletonCacheManager.Instance.Add<List<Map>>(maps, "Maps", 20);
}

if (SingletonCacheManager.Instance.Get<List<Playlist>>("Playlists") != null)
{
    playlists = SingletonCacheManager.Instance.Get<List<Playlist>>("Playlists");
}
else
{
    var p = await _apiService.GetPlaylists();
    playlists = p.ToList();
    SingletonCacheManager.Instance.Add<List<Playlist>>(playlists, "Playlists", 20);
}

这样的事情是否可能:

List<Map> maps = this.CacheHelper.GetCachedItems<Map>(key, lengthoftime);

然后 GetCachedItems 将检查缓存的项目并相应地检索。这似乎可行,但是当缓存项不存在并且我必须从 api/数据库中检索项目时,我不知道是否可以将其设为通用。

唯一的解决方案是对传入的类型使用 switch 语句?

switch(<T>type)
{
  case<Map>:
      return _mapRepository.FindBy(x => x.Active);
  case<Playlist>:
      return await _apiService.GetPlaylists();
}

感谢您的帮助。

最佳答案

我的解决方案是传入一个函数,该函数获取您需要缓存的数据作为 lambda 表达式。这样,缓存方法可以检查缓存并仅在需要时调用委托(delegate)。例如:

public T Get<T>(string key, Func<T> getItemDelegate, int duration) where T : class
{
    var cache = GetCache();

    var item = SingletonCacheManager.Instance.Get<ListMap>>(key) as T;

    if (item != null) return item;

    item = getItemDelegate();

    SingletonCacheManager.Instance.Add<T>(item, key, duration);

    return item;
}

现在您可以像这样一般地调用 Get 函数:

var maps = Get<List<Map>>(
    "Maps",
    () => _mapRepository.FindBy(x => x.Active).ToList(),
    20);

关于c# - C#中的通用缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41982292/

相关文章:

html - Mozilla Firefox 浏览器不加载样式表

c# - 查找列表中最常出现的项目的方法

c# - 如何在 C# 中的 REST API 中获取 PDF 文件

c# - 绑定(bind)到 DataTable 时更改 DataGrid 上的空值外观

c# - 通用方法与非通用方法 - 有任何性能优势吗?

javascript - 来自 Google Cloud 存储桶的图像不会立即更新

c# - 使用 dateTimePicker 在 DataGridView 中编辑日期

c# - 无法从 Func<T,T,T> 转换为 Func<T,T,T>

c# - 如何将派生类型列表分配给 C# 中的基类型列表?

caching - Appfabric缓存: Configuration Provider as single point of failure