public static VICycleDataGroup QueryVICycleDataGroup(int eventID, Meter meter, bool fullres = false) { string target = $"VICycleDataGroup-{eventID}"; if (s_memoryCache.Contains(target)) { return((VICycleDataGroup)s_memoryCache.Get(target)); } DataGroup dataGroup = QueryDataGroup(eventID, meter); Task <bool> viCycleDataGroupTask = new Task <bool>(() => { return (s_memoryCache.Add(target, Transform.ToVICycleDataGroup(new VIDataGroup(dataGroup), Fbase, false), new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(m_cacheSlidingExpiration) })); }); viCycleDataGroupTask.Start(); if (fullres) { viCycleDataGroupTask.Wait(); if (s_memoryCache.Contains(target)) { return((VICycleDataGroup)s_memoryCache.Get(target)); } } return(Transform.ToVICycleDataGroup(new VIDataGroup(dataGroup), Fbase, true)); }
/// <summary> /// Removes the specified cacheKey from the cache /// </summary> /// <param name="cacheKey"> </param> internal static void Remove(TKey cacheKey) { if (_cache.Contains(cacheKey as string)) { _cache.Remove(cacheKey as string); } }
public void Set(string key, V value, CacheItemPolicy cacheItemPolicy) { _locker.EnterWriteLock(); try { if (cache.Contains(key)) { //异步更新LRU顺序表 Task.Run(() => { var linkCache = _linkedList.FirstOrDefault(p => p.Key == key); if (linkCache != null) { LRUReSort(linkCache, true); } }); } else { var cacheData = new CacheData() { Key = key, AccessTime = DateTime.Now, WriteTime = DateTime.Now }; _linkedList.AddFirst(cacheData); } cacheItemPolicy.RemovedCallback = removedCallback; cache.Set(key, value, cacheItemPolicy); if (_linkedList.Count > _capacity) { cache.Remove(_linkedList.Last.Value.Key); } } finally { _locker.ExitWriteLock(); } }
private void StoreResultsInCache(Dictionary <string, ContentModel> results, List <string> LinksFound, List <BrokenPageModel> BrokenLinks, List <string> Domains) { if (cache.Contains("ResultsDictionary")) { cache.Remove("ResultsDictionary"); } cache.Add("ResultsDictionary", results, DateTime.Now.AddHours(1)); if (cache.Contains("LinksFound")) { cache.Remove("LinksFound"); } cache.Add("LinksFound", LinksFound, DateTime.Now.AddHours(1)); if (cache.Contains("BrokenLinks")) { cache.Remove("BrokenLinks"); } cache.Add("BrokenLinks", BrokenLinks, DateTime.Now.AddHours(1)); if (cache.Contains("Domains")) { cache.Remove("Domains"); } cache.Add("Domains", Domains, DateTime.Now.AddHours(1)); }
public Image this[string key, bool force, Action <Image> callBack] { get { lock (_lockObject) { if (force) { _innerDictionary.Remove(key); } else { if (_innerDictionary.Contains(key)) { return((Image)_innerDictionary[key]); } } // スタックに積む _waitStack.Push(new KeyValuePair <string, Action <Image> >(key, callBack)); } return(null); } }
public void Remove(string key) { if (_cache.Contains(key)) { _cache.Remove(key); } }
// GET /api/Identity/GetPasswordChallenge?requestId={requestId} public string GetPasswordChallenge(string requestId) { if (requestId == null) { return(null); } using (var generator = new RNGCryptoServiceProvider()) { var challengeBytes = new byte[16]; generator.GetBytes(challengeBytes); if (ChallengeCache.Contains(requestId)) { ChallengeCache[requestId] = challengeBytes; } else { CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10) }; ChallengeCache.Add(requestId, challengeBytes, policy); } return(EncodeToHexString(challengeBytes)); } }
public void Test005_BasicThreeWayLRUCacheSemanticExplicitIndexer() { var lruCache = new MemoryCache <int, int>(15, 3, k => k % 3); lruCache.SetPolicy(typeof(LruEvictionPolicy <,>)); Assert.AreEqual(lruCache.Capacity, 15); lruCache.Add(19, 19); // will go in way 1 lruCache.Add(1, 1); // will go in way 1 lruCache.Add(6, 6); // will go in way 0 lruCache.Add(4, 4); // will go in way 1 lruCache.Add(16, 16); // will go in way 1 lruCache.Add(5, 5); // will go in way 2 (should be first to be evicted in that way) lruCache.Add(18, 18); // will go in way 0 lruCache.Add(7, 7); // will go in way 1 lruCache.Add(15, 15); // will go in way 0 lruCache.Add(2, 2); // will go in way 2 lruCache.Add(14, 14); // will go in way 2 lruCache.Add(9, 9); // will go in way 0 lruCache.Add(20, 20); // will go in way 2 lruCache.Add(17, 17); // will go in way 2 lruCache.Add(12, 12); // will go in way 0 Assert.AreEqual(lruCache.Count, 15); Assert.AreEqual(lruCache.Contains(125), false); lruCache.Put(125, 125); // will go (after causing an evict) in way 2 Assert.AreEqual(lruCache.Contains(125), true); Assert.AreEqual(lruCache.Contains(5), false); Assert.AreEqual(lruCache.Count, 15); }
public void Getcount(int ID) { MemoryCache cache1 = MemoryCache.Default; if (!cache1.Contains("tp" + ID.ToString())) { lock (ID.ToString()) { if (!cache1.Contains("tp" + ID.ToString())) { string strtext = "select count(*) from tabvote where TabCanId=@ID"; MySqlParameter param = new MySqlParameter() { ParameterName = "ID", Value = ID, MySqlDbType = MySqlDbType.Int32 }; object count = MySQLCommon.ExecuteScalar(strtext, param); string strtxt2 = "update tabcandidate set Votes=@Count where Id=@ID"; MySqlParameter[] param2 = new MySqlParameter[] { new MySqlParameter() { ParameterName = "ID", Value = ID, MySqlDbType = MySqlDbType.Int32 }, new MySqlParameter() { ParameterName = "Count", Value = Convert.ToInt32(count), MySqlDbType = MySqlDbType.Int32 } }; MySQLCommon.ExecuteNonQuery(strtxt2, param2); cache1.Set("tp" + ID.ToString(), ID, DateTimeOffset.Now.AddMinutes(5)); } } } }
public UserDTO GetUserById(int id) { if (id == 42) { throw new HttpResponseException(HttpStatusCode.BadRequest); } if (id > 100) { throw new HttpResponseException(HttpStatusCode.NotFound); } if (_cache.Contains($"user-{id}")) { return(_cache.Get($"user-{id}") as UserDTO); } return(new UserDTO { Id = id, Name = RandomData.Names.Get(), Tag = RandomData.Tags.Get(), Company = RandomData.Companies.Get(), PreferredLanguage = RandomData.Langs.Get() }); }
/// <summary> /// Invoked whenever a cache key-value-pair is updated on another node. /// </summary> /// <param name="channel"></param> /// <param name="value"></param> private void OnKeyValueUpdated(RedisChannel channel, RedisValue value) { try { if (value.HasValue) { var message = FromByteBuffer <DistributedCacheMessage>(value, false)?.Object; if (message.SenderCacheName != Name) // don't process messages sent by the sender instance, as the job should have been synchronously { if (!_memoryCache.Contains(message.TransactionCacheKey)) // checks whether the message has already been processed (i.e., this node did the op directly) { SetInMemoryCache(message.Key, message.Buffer, message.ExpirationUtc); if (_fastMemcache.Contains(message.Key)) { _fastMemcache.Remove(message.Key); } Log(eCacheEvent.KeySetInMemory, message.Key); } } } } catch (Exception ex) { Log(ex); } }
/// <summary> /// 根据Id查询参选人的信息 /// </summary> /// <param name="Id"></param> /// <returns></returns> public DataTable GetTabCandidateWhere(int Id) { MemoryCache cache4 = MemoryCache.Default; if (!cache4.Contains("xy" + Id.ToString())) { lock (obj2) { if (!cache4.Contains("xy" + Id.ToString())) { string strText = "SELECT Id,`Name`,Sex,Age,School,Img,Player,Awards,Evaluation,Story,Reason,Votes,Rank FROM tabcandidate WHERE Id=@Id"; MySqlParameter param = new MySqlParameter() { ParameterName = "Id", Value = Id, MySqlDbType = MySqlDbType.Int32 }; DataTable dt = MySQLCommon.ExecuteDataTable(strText, param); cache4.Set("xy" + Id.ToString(), dt, DateTimeOffset.Now.AddMinutes(1)); } } } DataTable dt2 = cache4["xy" + Id.ToString()] as DataTable; return(dt2); }
internal static object GetCachedItem(string key, List <object> p, Func <object> action) { // Params if (p != null && p.Count > 0) { key = key + "/" + String.Join("|", p); } // If the item is in the cache, and the user didn't request to refresh it if (_cache.Contains(key)) { return(_cache.Get(key)); } // Item is not in cache... then create it var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddDays(1) }; // Set item in cache with key, and trigger action() _cache.Set(key, action(), cacheItemPolicy); // Return cached object return(_cache.Get(key)); }
internal bool GetFromCache <T>(string name, out T val) { try { this.cacheLocker.EnterReadLock(); if (cache.Contains(name)) { if (cache[name] is NullObject) { val = default(T); } else { val = (T)cache[name]; } return(true); } val = default(T); return(false); } finally { this.cacheLocker.ExitReadLock(); } }
public void Test003_BasicLRUCacheSemantic() { var lruCache = new MemoryCache <int, int>(); lruCache.SetPolicy(typeof(LruEvictionPolicy <,>)); Assert.AreEqual(lruCache.Capacity, AbstractCache.DefaultCapacity); lruCache.Add(19, 19); lruCache.Add(1, 1); lruCache.Add(6, 6); lruCache.Add(2, 2); lruCache.Add(16, 16); lruCache.Add(5, 5); lruCache.Add(18, 18); lruCache.Add(7, 7); lruCache.Add(15, 15); lruCache.Add(4, 4); lruCache.Add(14, 14); lruCache.Add(9, 9); lruCache.Add(13, 13); lruCache.Add(17, 17); lruCache.Add(12, 12); lruCache.Add(3, 3); Assert.AreEqual(lruCache.Count, 16); Assert.AreEqual(lruCache.Contains(123), false); lruCache.Add(123, 123); Assert.AreEqual(lruCache.Contains(123), true); Assert.AreEqual(lruCache.Contains(19), false); Assert.AreEqual(lruCache.Count, 16); }
private void RefreshGamesTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) { try { _refreshGamesTimer.Enabled = false; if (_userRequests.GetCount() == 0) { return; } var games = GameManager.Instance.Games.ToArray(); foreach (var game in games) { var strname = "hostrequest_" + game.Id; if (_userRequests.Contains(strname)) { _userRequests.Remove(strname); SendGameReady(game); } } } catch (Exception e) { Log.Error("[RefreshGamesTimerOnElapsed]", e); } finally { _refreshGamesTimer.Enabled = true; } }
public static T GetOrSet <T>(string key, Func <T> populator, TimeSpan expire, object parameters = null) { if (false == EnableCache) { return(populator()); } var parametersJson = parameters == null ? "" : JsonConvert.SerializeObject(parameters); var keyWithParameters = key + parametersJson; if (false == _cache.Contains(keyWithParameters)) { var item = populator(); if (ViolatesCachePolicy(item)) { return(item); } _cache.Add(keyWithParameters, item, DateTimeOffset.Now.Add(expire)); Log.Debug(new { Message = "Added item to cache", Method = "CacheService.GetOrSet<T>", ExpireTotalMinutes = expire.TotalMinutes, KeyWithParameters = keyWithParameters }); } return((T)_cache.Get(keyWithParameters)); }
private void StoreObject(string key, object obj, DateTime timeStamp) { if (!_cacheEnabled) { return; } if (_cache.Contains(key)) { return; } if (timeStamp > _cacheStartTime) // Verify that the cache has not been reenabled since the paxiom object was created. If so the paxiom may be obsolete and shall not be stored. { if (_paxiomCacheLogger.IsDebugEnabled) { _paxiomCacheLogger.DebugFormat("Adding key={0} to Cache", key); } lock (_cacheLock) { if (!_cache.Contains(key)) { _cache.Add(key, obj, new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0, PXWeb.Settings.Current.Features.SavedQuery.CacheTime, 0), Priority = CacheItemPriority.Default }); } } } }
/// <summary> /// Deletes the item from cache /// </summary> /// <param name="id">A string representing the id of the item in the cache to be deleted</param> /// <param name="cacheItemType">A cache item type</param> public override void CacheDeleteItem(string id, CacheItemType cacheItemType) { if (cacheItemType == CacheItemType.All || cacheItemType == CacheItemType.MarketDescription) { try { foreach (var fetchedVariant in _fetchedVariants) { if (fetchedVariant.Key.StartsWith(id)) { _fetchedVariants.TryRemove(id, out _); } } } catch (Exception e) { ExecutionLog.LogWarning($"Error deleting fetchedVariants for {id}", e); } if (_cache.Contains(id)) { CacheLog.LogDebug($"Delete variant market: {id}"); _cache.Remove(id); } } }
public static XLWorkbook ObterFolhaApr() { try { if (cache.Contains("FolhaAPR")) { var folhaApr = (XLWorkbook)cache.Get("FolhaAPR"); LimparFolhaAPR(folhaApr); return(folhaApr); } else { var caminhoFolhaApr = ConfigurationManager.AppSettings["caminhoFolhaApr"]; // A cache por default está como inexpirável ( Avaliar possibilidade de mudança) var cachePolicy = new CacheItemPolicy(); var folhaApr = new XLWorkbook(caminhoFolhaApr); var itemCacheFolhaApr = new CacheItem("FolhaAPR", folhaApr); cache.Add(itemCacheFolhaApr, cachePolicy); return(folhaApr); } } catch { throw; } }
public void TestRemoveFromCache() { _provider.Add("test", "value", DateTimeOffset.MaxValue, "region"); Assert.That(_store.Get("[region]test"), Is.EqualTo("value")); _provider.Remove("test", "region"); Assert.That(_store.Contains("[region]test"), Is.False); }
/// <summary> /// Получение данных. /// </summary> /// <param name="id">Идентификатор пользователя.</param> /// <returns>Данные авторизованного пользователя.</returns> public LoggedUserInfo Get(int id) { if (memoryCache.Contains(id.ToString())) { return(memoryCache.Get(id.ToString()) as LoggedUserInfo); } return(null); }
/// <summary> /// Gets the specified evm. /// </summary> /// <param name="evm">The evm.</param> /// <returns></returns> public static EntityViewModel Get(EntityViewModel evm) { if (!Cache.Contains(evm.EntityName)) { return(null); } return((EntityViewModel)Cache.Get(evm.EntityName)); }
private DataTable GetDataMeters(AdoDataConnection connection, DateTime date, string sortField, bool ascending) { DataTable table; if (s_memoryCache.Contains("Meters" + date.ToString())) { table = (DataTable)s_memoryCache.Get("Meters" + date.ToString()); } else { table = connection.RetrieveData(@" SELECT Meter.ID, Meter.Name, SUM(COALESCE(tbl.Expected,0)) as Expected, SUM(COALESCE(tbl.Missing,0)) as Missing, SUM(COALESCE(tbl.Latched,0)) as Latched, SUM(COALESCE(tbl.Unreasonable,0)) as Unreasonable FROM Meter JOIN ( SELECT Channel.ID, Channel.MeterId, Channel.Name, ChannelDataQualitySummary.Date, CAST(Channel.SamplesPerHour * 24 as int) as Expected, CAST((Channel.SamplesPerHour * 24) - COALESCE(ChannelDataQualitySummary.GoodPoints,0) - COALESCE(ChannelDataQualitySummary.LatchedPoints,0) - COALESCE(ChannelDataQualitySummary.UnreasonablePoints,0) - COALESCE(ChannelDataQualitySummary.NoncongruentPoints,0) as int) as Missing, CAST(COALESCE(ChannelDataQualitySummary.LatchedPoints, 0) as int) as Latched, CAST(COALESCE(ChannelDataQualitySummary.UnreasonablePoints, 0) as int) as Unreasonable FROM Channel JOIN ChannelDataQualitySummary ON Channel.ID = ChannelDataQualitySummary.ChannelID WHERE Channel.MeasurementTypeID IN (SELECT ID FROM MeasurementType WHERE Name = 'Voltage' OR Name = 'Current') AND Channel.MeasurementCharacteristicID IN (SELECT ID FROM MeasurementCharacteristic WHERE Name = 'RMS') ) as tbl on Meter.ID = tbl.MeterID WHERE Date = {0} GROUP BY Meter.Name, Meter.ID ", date); s_memoryCache.Add("Meters" + date.ToString(), table, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(10.0D) }); } if (!table.Select().Any()) { return(table); } else if (ascending) { return(table.Select().OrderBy(row => row[sortField]).CopyToDataTable()); } else { return(table.Select().OrderByDescending(row => row[sortField]).CopyToDataTable()); } }
// Login method to handle user logins and ensure it's done properly static UserAccount Login(MemoryCache cache) { Console.Write("Username (type \"Create\" to create account): "); string userName = Console.ReadLine(); // Create account if user types "Create" if (userName.Equals("Create")) { // Get a new username Console.Write("Creating user account...\nType new username: "******"Create" while (newUser.Equals("Create") || cache.Contains(newUser)) { Console.WriteLine("Invalid username (Could already be in use)"); Console.Write("Creating user account...\nType new username: "******"Username is not in system. Please try again"); } // Get UserAccount if username is in system else { // Get password from user Console.Write("Password for {0}: ", userName); string userPswd = Console.ReadLine(); // Get UserAccount from storage UserAccount user = (UserAccount)cache.Get(userName); // Check if the account password matches inputted password if (user.CheckPassword(userPswd)) { return(user); } else { Console.WriteLine("Incorrect Password"); } } // Rerun login if fails return(Login(cache)); }
/// <summary> /// Query an object from the cache. /// </summary> /// <exception cref="CacheEntryNotAddedException">Fired when a cache-entry cannot be found.</exception> /// <typeparam name="T">Type of the element to be retrieved</typeparam> /// <param name="key">Key</param> /// <returns>Cached object</returns> public override T Get <T>(string key) { if (_cacheInstance.Contains(key)) { return((T)_cacheInstance.Get(key)); } throw new CacheEntryNotFoundException(key); }
public T Get(string key) { if (!_cache.Contains(key)) { return(default(T)); } return((T)_cache[key]); }
/// <summary> /// 验证缓存项是否存在 /// </summary> /// <param name="key">缓存Key</param> /// <returns></returns> public bool Exists(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return(_cache.Contains(key)); }
internal async Task <T> GetBundle <T>(string name, bool forceRefetch) where T : class { Debug.WriteLine($"[{DateTimeOffset.UtcNow:O}] Requesting {typeof(T).Name} from {name}, force refetch: {forceRefetch}"); if (forceRefetch || !_valueCache.Contains(name)) { //The idea is to allow only one fetch per key, and should two threads ask for the same key, one thread waits and returns the value cached by the other key //Cannot use lock() {} here, as await is not allowed inside lock block. var semaphore = _locks.GetOrAdd(string.Intern(name), new SemaphoreSlim(1, 1)); await semaphore.WaitAsync(_kvWaitTime) .ConfigureAwait(false); //if there is no response by this time, the previous request has gone bad try { if (forceRefetch || !_valueCache.Contains(name)) { _valueCache.Remove(name); var value = await FetchValue <T>(name); if (value == null) { throw new NullReferenceException($"Key Vault request {typeof(T).Name} for \"{name}\" returned null!"); } var cachePolicy = new CacheItemPolicy(); if (_cachingDuration != TimeSpan.Zero) { cachePolicy.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMilliseconds(_cachingDuration.TotalMilliseconds); } _valueCache.Add(name, value, cachePolicy); Debug.WriteLine($"[{DateTimeOffset.UtcNow:O}] Added to cache: {name}"); return(value); } } finally { if (semaphore.CurrentCount == 0) { semaphore.Release(); } } } if (!(_valueCache.Get(name) is T cachedValue)) { throw new InvalidCastException($"Returned value from KeyVault cache is null or not castable to {typeof(T).Name}?!"); } Debug.WriteLine($"[{DateTimeOffset.UtcNow:O}] Fetched from cache: {name}"); return(cachedValue); }
/// <summary> /// Does item exists in the cache /// </summary> /// <param name="id">A <see cref="URN" /> representing the id of the item to be checked</param> /// <param name="cacheItemType">A cache item type</param> /// <returns><c>true</c> if exists, <c>false</c> otherwise</returns> public override bool CacheHasItem(URN id, CacheItemType cacheItemType) { if (cacheItemType == CacheItemType.All || cacheItemType == CacheItemType.Competitor || cacheItemType == CacheItemType.Player) { return(_cache.Contains(id.ToString())); } return(false); }
public void Test003_CacheAddIgnoresKeyDuplicatesAndReturnsFalse() { var nonEmptyCache = new MemoryCache<int, int>(); nonEmptyCache.Add(3, 3); nonEmptyCache.Add(1, 1); nonEmptyCache.Add(5, 5); nonEmptyCache.Add(4, 4); Assert.AreEqual(nonEmptyCache.Contains(2), false); Assert.AreEqual(nonEmptyCache.Contains(5), true); Assert.AreEqual(nonEmptyCache.Contains(4), true); Assert.AreEqual(nonEmptyCache.Remove(4), true); Assert.AreEqual(nonEmptyCache.Add(5, 123), false); Assert.AreEqual(nonEmptyCache.Add(4, 6), true); Assert.AreEqual(nonEmptyCache.Get(5), 5); Assert.AreEqual(nonEmptyCache.Get(4), 6); }
public void Test004_CachePutIgnoresKeyDuplicatesAndAllowsOverwrite() { var nonEmptyCache = new MemoryCache<int, int>(); nonEmptyCache.Add(3, 3); nonEmptyCache.Add(1, 1); nonEmptyCache.Add(5, 5); nonEmptyCache.Add(4, 4); Assert.AreEqual(nonEmptyCache.Contains(2), false); Assert.AreEqual(nonEmptyCache.Contains(5), true); Assert.AreEqual(nonEmptyCache.Contains(4), true); Assert.AreEqual(nonEmptyCache.Remove(4), true); nonEmptyCache.Put(5, 123); Assert.AreEqual(nonEmptyCache[5], 123); Assert.AreEqual(nonEmptyCache.Add(4, 6), true); Assert.AreEqual(nonEmptyCache[4], 6); nonEmptyCache.Put(4, 7); Assert.AreEqual(nonEmptyCache[4], 7); }
public void Test003_BasicLRUCacheSemantic() { var lruCache = new MemoryCache<int, int>(); lruCache.SetPolicy(typeof(LruEvictionPolicy<,>)); Assert.AreEqual(lruCache.Capacity, AbstractCache.DefaultCapacity); lruCache.Add(19, 19); lruCache.Add(1, 1); lruCache.Add(6, 6); lruCache.Add(2, 2); lruCache.Add(16, 16); lruCache.Add(5, 5); lruCache.Add(18, 18); lruCache.Add(7, 7); lruCache.Add(15, 15); lruCache.Add(4, 4); lruCache.Add(14, 14); lruCache.Add(9, 9); lruCache.Add(13, 13); lruCache.Add(17, 17); lruCache.Add(12, 12); lruCache.Add(3, 3); Assert.AreEqual(lruCache.Count, 16); Assert.AreEqual(lruCache.Contains(123), false); lruCache.Add(123, 123); Assert.AreEqual(lruCache.Contains(123), true); Assert.AreEqual(lruCache.Contains(19), false); Assert.AreEqual(lruCache.Count, 16); }
public void Test005_BasicThreeWayLRUCacheSemanticExplicitIndexer() { var lruCache = new MemoryCache<int, int>(15, 3, k => k % 3); lruCache.SetPolicy(typeof(LruEvictionPolicy<,>)); Assert.AreEqual(lruCache.Capacity, 15); lruCache.Add(19, 19); // will go in way 1 lruCache.Add(1, 1); // will go in way 1 lruCache.Add(6, 6); // will go in way 0 lruCache.Add(4, 4); // will go in way 1 lruCache.Add(16, 16); // will go in way 1 lruCache.Add(5, 5); // will go in way 2 (should be first to be evicted in that way) lruCache.Add(18, 18); // will go in way 0 lruCache.Add(7, 7); // will go in way 1 lruCache.Add(15, 15); // will go in way 0 lruCache.Add(2, 2); // will go in way 2 lruCache.Add(14, 14); // will go in way 2 lruCache.Add(9, 9); // will go in way 0 lruCache.Add(20, 20); // will go in way 2 lruCache.Add(17, 17); // will go in way 2 lruCache.Add(12, 12); // will go in way 0 Assert.AreEqual(lruCache.Count, 15); Assert.AreEqual(lruCache.Contains(125), false); lruCache.Put(125, 125); // will go (after causing an evict) in way 2 Assert.AreEqual(lruCache.Contains(125), true); Assert.AreEqual(lruCache.Contains(5), false); Assert.AreEqual(lruCache.Count, 15); }
public void RemoveAggregateFromCacheOnConcurrencyException() { var aggregate = new FakeAggregate(); var decoratedAggregateStore = new Mock<IStoreAggregates>(); var memoryCache = new MemoryCache(Guid.NewGuid().ToString()); var cachedAggregateStore = new CachedAggregateStore(decoratedAggregateStore.Object, TimeSpan.FromMinutes(1), memoryCache); // ReSharper disable AccessToDisposedClosure using (var context = new CommandContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty)) { memoryCache.Add(aggregate.CacheKey, aggregate, new CacheItemPolicy()); decoratedAggregateStore.Setup(mock => mock.Save(It.Is<Aggregate>(copy => !ReferenceEquals(aggregate, copy)), context)).Throws<ConcurrencyException>(); Assert.Throws<ConcurrencyException>(() => cachedAggregateStore.Save(aggregate, context)); Assert.False(memoryCache.Contains(aggregate.CacheKey)); } // ReSharper restore AccessToDisposedClosure }
public void Test002_BasicLFUCacheSemantic() { var lfuCache = new MemoryCache<int, string>(); lfuCache.SetPolicy(typeof(LfuEvictionPolicy<,>)); Assert.AreEqual(lfuCache.Capacity, AbstractCache.DefaultCapacity); var data = Enumerable.Range(0, AbstractCache.DefaultCapacity + 1). Aggregate(new StringBuilder(), (sb, i) => sb.Append(i > 0 ? String.Format(",String {0}", i) : String.Empty)). ToString(). Split(','); // Cache all the (16) non-empty strings for (var i = 1; i < data.Length; i++) { lfuCache.Add(i, data[i]); } // Use all the (16) non-empty strings four times... for (var use = 1; use <= 4; use++) { for (var i = 1; i < data.Length; i++) { // ... except for "String 3", used only twice... if (i == 3) { if (use <= 2) { var s = lfuCache.Get(i); } } // ... and for "String 9", used only once else if (i == 9) { if (use <= 1) { var s = lfuCache.Get(i); } } else { var s = lfuCache.Get(i); } } } lfuCache.Add(17, "String 17"); Assert.AreEqual(lfuCache.Contains(9), false); Assert.AreEqual(lfuCache.Contains(17), true); var used4times = lfuCache.Get(17); used4times = lfuCache.Get(17); used4times = lfuCache.Get(17); used4times = lfuCache.Get(17); lfuCache.Put(18, "String 18"); Assert.AreEqual(lfuCache.Contains(3), false); Assert.AreEqual(lfuCache.Contains(17), true); Assert.AreEqual(lfuCache.Contains(18), true); }