2

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.

Onosa
  • 1,275
  • 1
  • 12
  • 28
  • is it possible the set is being done on another thread? What if you do a wait and check again? – Dustin Davis Aug 26 '11 at 19:33
  • There is a lock (this){...} around the code above, so I do not believe it would be possible. – Onosa Aug 26 '11 at 19:38
  • That isn't going to help anything. Maybe if you use lock(_cache){}. Did you test this theory by waiting before trying? – Dustin Davis Aug 26 '11 at 19:41
  • DustinDavis, I appreciate your help however I do not believe I catch your meaning. What do you mean wait and check again? Also, lock(this) appears to be working fine. I ran a unit test that span up multiple threads that called my "AddLocationToCache" method and they all ran sequentially. Also I log each exception and when "AddLocationToCache" is called multiple times, the timestamp on each log indicates a sequential execution. – Onosa Aug 26 '11 at 19:52
  • is CacheKey.LOCATIONS a string? – Shiraz Bhaiji Aug 26 '11 at 21:13
  • Yes. "Locations" is the value. – Onosa Aug 26 '11 at 21:18

1 Answers1

1

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

Jeremy
  • 26
  • 1