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

时间:2018-12-23 14:18:55

标签: 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);
    }
}

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

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

1 个答案:

答案 0 :(得分:1)

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...
}