public static IDataReader AddToCache(ISqlQuery query, IDataReader data) { ICacheKey key = new CacheKey(query); CachedDataReader cached = new CachedDataReader(data); int newSize = cached.Size() + key.Query.Length; ICacheItem item; if (newSize < CacheObjectSizeLimit) { while (CacheSize + newSize > CacheSizeLimit && QueryOrder.Count > 0) { ICacheKey oldestKey = QueryOrder.Peek(); if (!RemoveFromCache(oldestKey)) { break; } } if (QueryOrder.Count == 0 && CacheSize != 0) { CacheSize = 0; QueryResultCache.Clear(); // this should be logged but thrwing an error seems too much... test the hellout of this? } // It is possible that we failed to remove it from the cache, so just bail out // if still won't fit if (CacheSize + newSize <= CacheSizeLimit) { item = new CacheItem(cached, newSize); if (QueryResultCache.TryAdd(key, item)) { QueryOrder.Enqueue(key); } } else { } } // whether or not we end up caching the datareader, we must return the in-memory copy because you can't go back // after reading a datareader. We only try to cache when buffering is enabled, so nothing's really lost. return cached; }
public static bool TryGetCachedData(ISqlQuery query, out IDataReader data) { var key = new CacheKey(query); ICacheItem cached; if (QueryResultCache.TryGetValue(key, out cached)) { if (cached.Expired) { RemoveFromCache(key); data = null; return false; } else { CachedDataReader reader = ((CacheItem)cached).Data; reader.Reset(); data = new CachedDataReaderView(reader); return true; } } else { data=null; return false; } }
public static bool RemoveFromCache(ISqlQuery query) { ICacheKey key = new CacheKey(query); return RemoveFromCache(key); }