Search code examples
c#objectcache

ObjectCache does not contain item immediently after setting it consistently


All- I am attempting to create a server-side cache using the new ObjectCache object. For whatever reason, the following is throwing an exception...

_cache.Set(CacheKey.LOCATIONS, cachedLocations, DateTimeOffset.Now.AddHours(2));
                    if (!_cache.Contains(CacheKey.LOCATIONS))
                        throw new Exception("Did not add location to the cache.");

_cache is instantiated in the following way on the service layer...

private ObjectCache _cache = MemoryCache.Default;

This exception occures every time the cache is being set, except the first time. The exception is the one shown in the code... "Did not add location to the cache."

---Edit note. ObjectCache was static, but there is no need for it to be static since MemoryCache.Default is static.


Solution

  • You should use the Add() method to create a new entry in the cache. The Set() method involves the key already exists.