【问题标题】:MemoryCache Contains() thread-safetyMemoryCache Contains() 线程安全
【发布时间】:2012-10-24 09:01:19
【问题描述】:

MemoryCache 是一个线程安全的类,根据this 文章。但我不明白它在特定情况下会如何表现。例如我有代码:

static private MemoryCache _cache = MemoryCache.Default;

...

if (_cache.Contains("Test"))
{
    return _cache.Get("Test") as string;
}
  1. 在我调用Contains() 之后元素的生存时间是否会过期,所以null 值将被返回?
  2. 在我调用Contains() 之后,另一个线程是否可以删除项目,所以null 值将被返回?

【问题讨论】:

    标签: c# caching concurrency thread-safety


    【解决方案1】:

    是的,是的,这些是常见的竞争条件。如果只需将代码编写为

    就可以避免它们
    var test = _cache.Get("Test");
    if (test != null) {
        return test as string;
    }
    

    【讨论】:

    • 如果我想在过期项目中写入新值,我只需使用else { string result = 'some data from my database'; _cache.Set("Test", result, DateTimeOffset.UtcNow.AddSeconds(30)); return result; },一切都会好起来的。对吗?
    • @ChruS:不,在这种情况下,为了避免竞争条件,您应该改用AddOrGetExisting
    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多