gpt4 book ai didi

c# - 在 .Net Core 3.1 中使 IDistributedCache 线程安全

转载 作者:行者123 更新时间:2023-12-03 23:08:22 25 4
gpt4 key购买 nike

我需要使用 IDistributedCache在我的应用程序中,它可能是 MemoryDistributedCacheRedisCache作为底层实现。我的理解是这些不是线程安全的,所以我创建了自己的包装器,使用 ReaderWriterLockSlim .
ReaderWriterLockSlim允许多个线程进行读取或独占访问进行写入。现在我想知道它是否适合这项工作以及是否 MemoryDistributedCacheRedisCache读取方法是线程安全的。

至于整体解决方案 - 我知道从像 Redis 这样的分布式缓存中存储和读取值需要时间。但我没有太多选择,因为我存储的值获取和管理的速度更慢。

这是片段:

...
public async Task<byte[]> GetAsync(string key, CancellationToken token = new CancellationToken())
{
_cacheLock.EnterReadLock();
try
{
return await _cache.GetAsync(GetCacheKey(key), token);
}
finally
{
_cacheLock.ExitReadLock();
}
}

public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = new CancellationToken())
{
_cacheLock.EnterWriteLock();
try
{
await _cache.SetAsync(GetCacheKey(key), value, options, token);
}
finally
{
_cacheLock.ExitWriteLock();
}
}

public async Task RemoveAsync(string key, CancellationToken token = new CancellationToken())
{
_cacheLock.EnterWriteLock();
try
{
await _cache.RemoveAsync(GetCacheKey(key), token);
}
finally
{
_cacheLock.ExitWriteLock();
}
}

最佳答案

全部 IDistributedCache实现应该是线程安全的。如果不是,那么请创建一个错误报告以修复它。

即使其中之一不是线程安全的,使用 ReaderWriterLockSlim守卫async代码无效。来自 the docs :

ReaderWriterLockSlim has managed thread affinity; that is, each Thread object must make its own method calls to enter and exit lock modes. No thread can change the mode of another thread.



最简单的解决方法是使用 SemaphoreSlim而不是 ReaderWriterLockSlim .

关于c# - 在 .Net Core 3.1 中使 IDistributedCache 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60792384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com