【问题标题】:how to use MemoryCache Class to cache and get a list in asp.net coreasp.net core中如何使用MemoryCache类缓存并获取列表
【发布时间】:2021-09-02 06:17:17
【问题描述】:

我可以通过创建“IMeomoryCache”类的实例来获取缓存对象,如下所示:

_memoryCache.Get<Users>(id);

1.但是如何获取使用该类的用户列表?

2.第二个问题,如果列表没有缓存,如何设置缓存?

【问题讨论】:

标签: c# caching .net-core memorycache


【解决方案1】:

您可以使用将缓存对象作为输出参数返回的 TryGetValue 方法。请参考以下示例:-

List<User> users;
string key = "usersCacheKey";
//TryGetValue will get the item from cache and assign it to users variable.
//It will return false if item is not found.
if(!_memoryCache.TryGetValue<List<User>>(key, out users){
  //item not found in cache. set the cache item here
  users = new List<User>();
  _memoryCache.Set<List<User>>(key, users);
}

关于如何在 ASP.NET Core 5.0 中使用内存缓存的更多信息,请参考以下链接:- Cache in-memory in ASP.NET Core

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多