MemoryCache is a thread-safe class, according to this article. But I don’t understand how it will behave in a specific situation. For example I have the code:
static private MemoryCache _cache = MemoryCache.Default;
...
if (_cache.Contains("Test"))
{
return _cache.Get("Test") as string;
}
- Can element’s living time expire just after I call
Contains()sonullvalue will be returned? - Can another thread remove item just after I call
Contains()sonullvalue will be returned?
Yes and yes, these are common race conditions. You can avoid them if by simply writing the code as