如何在asp.net core中使用MemoryCache类来缓存并获取列表

问题描述 投票:0回答:1

我可以通过创建

IMemoryCache
类的实例来获取缓存的对象,如下所示:

_memoryCache.Get<Users>(id);
  1. 如何获取使用此类的用户列表?

  2. 如果列表没有缓存,如何缓存?

c# caching .net-core memorycache
1个回答
3
投票

您可以使用 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 中使用内存缓存的更多信息:- 在 ASP.NET Core 中缓存内存中

© www.soinside.com 2019 - 2024. All rights reserved.