protected override void ExitLock() { if (CacheLock.IsWriteLockHeld) { CacheLock.ExitWriteLock(); } }
/// <summary> /// Clear all cached values /// </summary> public void Clear() { CacheLock.EnterWriteLock(); try { Cache.Clear(); } finally { CacheLock.ExitWriteLock(); } }
/// <summary> /// Remove cached value /// </summary> /// <param name="key">Cache key</param> public void Remove(TKey key) { RevokeExpires(); CacheLock.EnterWriteLock(); try { Cache.Remove(key); } finally { CacheLock.ExitWriteLock(); } }
protected override void ExitLock() { if (CacheLock.IsWriteLockHeld) { CacheLock.ExitWriteLock(); } if (CacheLock.IsUpgradeableReadLockHeld) { CacheLock.ExitUpgradeableReadLock(); } }
/// <summary> /// Put value to cache /// </summary> /// <param name="key">Cache key</param> /// <param name="value">Cache value</param> /// <param name="keepTime">Keep time</param> public void Put(TKey key, TValue value, TimeSpan keepTime) { RevokeExpires(); if (keepTime == TimeSpan.Zero) { return; } var now = DateTime.UtcNow; CacheLock.EnterWriteLock(); try { Cache[key] = Pair.Create(value, now + keepTime); } finally { CacheLock.ExitWriteLock(); } }
/// <summary> /// Revoke expired values if the check interval has elapsed /// </summary> protected void RevokeExpires() { var now = DateTime.UtcNow; if ((now - LastRevokeExpires) < RevokeExpiresInterval) { return; } CacheLock.EnterWriteLock(); try { if ((now - LastRevokeExpires) < RevokeExpiresInterval) { return; // double check } LastRevokeExpires = now; var expireKeys = Cache.Where(c => c.Value.Second < now).Select(c => c.Key).ToList(); foreach (var key in expireKeys) { Cache.Remove(key); } } finally { CacheLock.ExitWriteLock(); } }