MemoryCache
是一个线程安全的类。但我不明白它在特定情况下会如何表现。例如,我有代码:
static private MemoryCache _cache = MemoryCache.Default;
...
if (_cache.Contains("Test"))
{
return _cache.Get("Test") as string;
}
Contains()
之后,元素的生存时间是否会过期,因此会返回null
值? Contains()
之后删除另一个帖子,这样会返回null
值吗? 答案 0 :(得分:3)
是的,是的,这些是常见的竞争条件。如果只是将代码编写为
,则可以避免它们var test = _cache.Get("Test");
if (test != null) {
return test as string;
}