We also saw this problem in our code. We solve this by overriding the Get method to catch expectations, and then repeat the call N times before returning to the direct SQL query.
Here is the code we use to get data from the cache
private static bool TryGetFromCache(string cacheKey, string region, out GetMappingValuesToCacheResult cacheResult, int counter = 0) { cacheResult = new GetMappingValuesToCacheResult(); try { // use as instead of cast, as this will return null instead of exception caused by casting. if (_cache == null) return false; cacheResult = _cache.Get(cacheKey, region) as GetMappingValuesToCacheResult; return cacheResult != null; } catch (DataCacheException dataCacheException) { switch (dataCacheException.ErrorCode) { case DataCacheErrorCode.KeyDoesNotExist: case DataCacheErrorCode.RegionDoesNotExist: return false; case DataCacheErrorCode.Timeout: case DataCacheErrorCode.RetryLater: if (counter > 9) return false; // we tried 10 times, so we will give up. counter++; Thread.Sleep(100); return TryGetFromCache(cacheKey, region, out cacheResult, counter); default: EventLog.WriteEntry(EventViewerSource, "TryGetFromCache: DataCacheException caught:\n" + dataCacheException.Message, EventLogEntryType.Error); return false; } } }
Then, when we need to get something from the cache, we do:
TryGetFromCache(key, region, out cachedMapping)
This allows us to use Try methods that encapsulate exceptions. If it returns false, we know what is wrong in the cache, and we can access SQL directly.
Frode stenstrรธm
source share