asp.net-mvc - 如何在Asp.net Core中将缓存更新为并发请求?

标签 asp.net-mvc caching asp.net-core

我在Asp.net核心中使用内存缓存并使用自定义业务。我需要角色列表以及内存中角色的相关数据。

我对内存中的缓存角色使用以下方法:

public void Add(Role role)
{
    lock (_lockObject)
    {
        var dictionary = _cache.Get<Dictionary<string, List<RoleViewModel>>>(CacheKeys.RoleCache);

        if (dictionary.ContainsKey(role.Id))
        {
            dictionary[role.tId].Add(new RoleCacheViewModel(role));
        }
        else
        {
            dictionary.Add(
                role.Id,
                new List<RoleCacheViewModel> { new RoleCacheViewModel(role) });
        }

        _cache.Set(CacheKeys.RoleCache, dictionary);
    }
}

因此,我有很多请求,我需要它来缓存在内存中。对于并发请求,我正在使用如下所示的锁对象。

是正确的方法还是我可以使用更好的方法?

最佳答案

MemoryCache类是线程安全的(请参见-https://github.com/aspnet/Extensions/blob/master/src/Caching/Memory/src/MemoryCache.cs#L23),因此您无需在插入高速缓存之前锁定。

插入缓存很简单:

_cache.GetOrCreate<Role>(role.Id, entry => entry.Value = role);

然后从缓存中获取值将是:
if(_cache.TryGetValue<Role>(id, out var role))
{
    // your code here...
}

关于asp.net-mvc - 如何在Asp.net Core中将缓存更新为并发请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53904340/

相关文章:

asp.net-core - 在 ASP.NET Identity 中将电子邮件设置为用户名

asp.net-core - 使用IdentityServer4的Swagger UI授权返回无效的redirect_uri

facebook - 存储 Facebook API 数据

java - SpEL - 错误 : Method cannot be found on type

Django + 雷迪斯 : How to invalidate cache for just one specific element

postgresql - EF Core 2.0 更新 - 跟踪问题

c# - 在 Controller 中实现 System.Web.Caching.Cache 对象来缓存特定查询

asp.net - 默认模型绑定(bind)器不绑定(bind)我的模型类

c# - SelectedValues 在 MultiSelectList mvc 中不起作用

asp.net-mvc - 如何配置 Nhibernate 不在当前 session 中保存对象