Пример #1
0
        public async static System.Threading.Tasks.Task <bool> Load(Env env)
        {
            try
            {
                var obj = env.Engine.FindById("ky", ID);
                //   await System.Threading.Tasks.Task.Delay(1000);
                if (obj != null)
                {
                    var o = BsonMapper.Global.ToObject <BL>(obj);

                    foreach (var a in o.v)
                    {
                        var obj_late = new System.Runtime.Caching.CacheItemPolicy();
                        obj_late.AbsoluteExpiration = o.off[a.Key];

                        obj_late.RemovedCallback = Exp.cb;
                        cache.Add(a.Key, a.Value, obj_late);

                        //   cache[a.Key] = a.Value;
                    }
                }
                if (cache == null)
                {
                    cache = System.Runtime.Caching.MemoryCache.Default;
                }
            }
            catch
            {
            }
            // await Back(env);
            return(true);
        }
        /// <summary>
        /// Puts the specified value in the cache.
        /// </summary>
        /// <param name="key">The cache key.</param>
        /// <param name="value">The value to put into the cache.</param>
        /// <param name="ttl">The time-to-live for the cache entry.</param>
        public void Put(string key, object value, Ttl ttl)
        {
#if PORTABLE
            using (Microsoft.Extensions.Caching.Memory.ICacheEntry entry = _cache.CreateEntry(key)) {
                entry.Value = value;
                if (ttl.SlidingExpiration)
                {
                    entry.SlidingExpiration = ttl.Timespan;
                }
                else
                {
                    entry.AbsoluteExpirationRelativeToNow = ttl.Timespan;
                }
            }
#else
            System.Runtime.Caching.CacheItemPolicy cacheItemPolicy = new System.Runtime.Caching.CacheItemPolicy();
            if (ttl.SlidingExpiration)
            {
                cacheItemPolicy.SlidingExpiration = ttl.Timespan;
            }
            else
            {
                cacheItemPolicy.AbsoluteExpiration = SystemClock.DateTimeOffsetUtcNow().Add(ttl.Timespan);
            }
            _cache.Set(key, value, cacheItemPolicy);
#endif
        }
Пример #3
0
        public void Execute(StringScanner s, Env env, out bool b, out object obj2)
        {
            b    = false;
            obj2 = null;
            var key   = s.Scan(@"exp.([\w$]*).ss\s*", 1);
            var value = s.Scan(".*").TrimToNull();

            int.TryParse(value, out var ss);

            var obj = new System.Runtime.Caching.CacheItemPolicy();
            var l   = System.DateTime.Now.AddSeconds(ss);

            obj.AbsoluteExpiration = l;
            obj.RemovedCallback    = cb;

            var os = Open.cache.Get(key);//, value, obj);

            if (os == null)
            {
                env.Display.WriteError(new Exception($"{key}不存在"));
                return;
            }
            Open.cache.Set(key, os, obj);

            //    var new_key = new key_value { key = key, value = value };

            //var doc=    LiteDB.BsonMapper.Global.ToDocument(typeof(key_value), new_key);
            Open.kw[key] = obj;


            //      var bools= env.Engine.Upsert("key_value",(doc),BsonType.ObjectId);
            //    var wrrw =System.Linq.Enumerable.ToList(doc.Values)[0].RawValue;
            env.Display.WriteLine($"设定 {key} 过期时间为 {l}");
        }
Пример #4
0
        /// <summary>
        /// Forcefully re-creates the object under the given unique key value using object renewal logic.
        /// The method is not optimised for cases when executing the re-creation logic will result with null.
        /// </summary>
        /// <param name="key">Unique identificator.</param>
        /// <returns>Returns the instance, if failed null.</returns>
        /// <exception cref="ArgumentNullException">thrown, if <paramref name="key"/> is null.</exception>
        public object ForceRenewal(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            CacheRegistryLogic logic;
            object             item = null;

            _lock.EnterUpgradeableReadLock();
            try
            {
                if (_logicCache.TryGetValue(key, out logic))
                {
                    logic.Lock.EnterUpgradeableReadLock(); // entry, update lock
                    try
                    {
                        item = _objectCache.Get(key);

                        if (item == null)
                        {
                            item = logic.ObjectRenewalLogic();

                            if (item != null)
                            {
                                logic.Lock.EnterWriteLock(); // entry, write lock
                                try
                                {
                                    System.Runtime.Caching.CacheItemPolicy cacheItemPolicy = new System.Runtime.Caching.CacheItemPolicy()
                                    {
                                        AbsoluteExpiration = DateTimeOffset.UtcNow.Add(logic.Expiration),
                                    };

                                    _objectCache.Set(key, item, cacheItemPolicy);
                                }
                                catch { }
                                finally
                                {
                                    logic.Lock.ExitWriteLock(); // entry, write unlock
                                }
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        logic.Lock.ExitUpgradeableReadLock(); // entry, update unlock
                    }
                }
            }
            catch { }
            finally
            {
                _lock.ExitUpgradeableReadLock();
            }

            return(item);
        }
Пример #5
0
        public T Set <T>(string key, CacheInfo <T> cache) where T : class
        {
            var oldCache  = _cache.Get(key);
            var cacheItem = new System.Runtime.Caching.CacheItem(key, cache.Value);
            var policy    = new System.Runtime.Caching.CacheItemPolicy();

            policy.SlidingExpiration = cache.SlidingExpiration;
            _cache.Set(cacheItem, policy);
            return(oldCache == null ? null : (T)oldCache);
        }
Пример #6
0
        // private CacheEntryRemovedCallback callback = null;

        public static void AddToCache(String CacheKeyName, Object CacheItem, CachePriorityType MyCacheItemPriority)
        {
            System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy();
            policy.Priority = (MyCacheItemPriority == CachePriorityType.Default) ?
                              System.Runtime.Caching.CacheItemPriority.Default : System.Runtime.Caching.CacheItemPriority.NotRemovable;
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(0.5);

            // Add inside cache
            cache.Set(CacheKeyName, CacheItem, policy);
        }
        public void AddOrReplace(string key, object value)
        {
            Ensure.StringArgumentNotNullAndNotEmpty(key, nameof(key));
            Ensure.ArgumentNotNull(value, nameof(value));

            System.Runtime.Caching.CacheItem       item   = new System.Runtime.Caching.CacheItem(key, value);
            System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy();
            policy.RemovedCallback = x => OnCacheItemRemoved(new CacheItemRemovedEventArgs(x.CacheItem.Key, x.CacheItem.Value));
            cache.Set(item, policy);
        }
Пример #8
0
        public static object AddOrUpdate(string cacheKey, object value)
        {
            System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy();
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddDays(1);
            object existing = System.Runtime.Caching.MemoryCache.Default.AddOrGetExisting(cacheKey, value, policy);

            if (existing != null)
            {
                System.Runtime.Caching.MemoryCache.Default[cacheKey] = value;
            }
            return(value);
        }
Пример #9
0
        public CapAdministration()
        {
            if (ConfigSingleton.NegativeCacheItemLifetime.TotalSeconds > 0)
            {
                _negativeCache     = System.Runtime.Caching.MemoryCache.Default;
                _negativeCacheLock = new ReaderWriterLockSlim();

                _negativeCachePolicy = new System.Runtime.Caching.CacheItemPolicy {
                    SlidingExpiration = ConfigSingleton.NegativeCacheItemLifetime,
                };
            }
        }
Пример #10
0
        private void WriteToCache(String userAgent, DeviceInfo device)
        {
            var uaHash       = HashUserAgentString(userAgent);
            var _cachePolicy = new System.Runtime.Caching.CacheItemPolicy()
            {
                AbsoluteExpiration =
                    new DateTimeOffset(
                        DateTime.UtcNow.AddSeconds(_durationInSeconds))
            };

            _cache.Add(uaHash, device, _cachePolicy);
        }
        private void GivenPolicyWithSlidingExpirationOf(TimeSpan expiration)
        {
            var policy = new System.Runtime.Caching.CacheItemPolicy {
                SlidingExpiration = expiration
            };

            _cacheItemPolicyConverterMock = new Mock <ICacheItemPolicyConverter>();
            _cacheItemPolicyConverterMock
            .Setup(e => e.Convert(It.IsAny <CacheItemPolicy>()))
            .Returns(policy);

            _cacher = new MemoryCacher(_cacheItemPolicyConverterMock.Object, _cacheItemPriorityMock.Object);
        }
        public void AddOrReplace(string key, object value, TimeSpan timeout)
        {
            Ensure.StringArgumentNotNullAndNotEmpty(key, nameof(key));
            Ensure.ArgumentNotNull(value, nameof(value));

            System.Runtime.Caching.CacheItem item = new System.Runtime.Caching.CacheItem(key, value);

            System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy();
            policy.SlidingExpiration = timeout;
            // Set non-removable flag to prevent cache item removals due to other reasonse apart from the timeout. e.g. low memory
            policy.Priority        = System.Runtime.Caching.CacheItemPriority.NotRemovable;
            policy.RemovedCallback = x => OnCacheItemRemoved(new CacheItemRemovedEventArgs(x.CacheItem.Key, x.CacheItem.Value));

            cache.Set(item, policy);
        }
Пример #13
0
        void ICache.Set(string key, CacheInfo cache)
        {
            var cacheItem = new System.Runtime.Caching.CacheItem(key, cache.Value);
            var policy    = new System.Runtime.Caching.CacheItemPolicy();

            if (cache.AbsoluteExpiration.Ticks > 0)
            {
                policy.AbsoluteExpiration = cache.AbsoluteExpiration;
            }
            if (cache.SlidingExpiration.Ticks > 0)
            {
                policy.SlidingExpiration = cache.SlidingExpiration;
            }
            _cache.Set(cacheItem, policy);
        }
Пример #14
0
        public MemoryCache(int minutes) : base(minutes)
        {
            this.minutes = minutes;
            if (_memoryCache == null)
            {
#if !(NETCORE || CORE)
                _memoryCache     = System.Runtime.Caching.MemoryCache.Default;
                _cacheItemPolicy = new System.Runtime.Caching.CacheItemPolicy();
                _cacheItemPolicy.SlidingExpiration = TimeSpan.FromMinutes(this.minutes);
#else
                _memoryCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()
                {
                });
#endif
            }
        }
Пример #15
0
        /// <summary>
        /// Thêm số lượt ăn theo tài khoản
        /// </summary>
        /// <param name="totalSecond"></param>
        /// <param name="action"></param>
        private void AddStatusFrequency(int totalSecond, string action)
        {
            string ip = IPAddressHelper.GetClientIP();

            System.Runtime.Caching.ObjectCache     cache  = System.Runtime.Caching.MemoryCache.Default;
            System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy()
            {
                AbsoluteExpiration = DateTime.Now.AddSeconds(totalSecond)
            };
            object cacheCounter = cache.Get("@Post" + ip.ToLower() + AccountSession.AccountName + "_" + action);

            if (cacheCounter == null)
            {
                cache.Set("@Post" + ip.ToLower() + AccountSession.AccountName + "_" + action, 1, policy);
            }
            cache.Set("@Post" + ip.ToLower() + AccountSession.AccountName + "_" + action, Convert.ToInt32(cacheCounter) + 1, policy);
        }
Пример #16
0
        /// <summary>
        /// Kiểm tra tài khoản thực hiện 1 hành động trong số giây (tự cộng số lượt mỗi lần gọi hàm check)
        /// </summary>
        /// <param name="accountName">Tên tài khoản</param>
        /// <param name="totalSecond">Số giây kiểm tra</param>
        /// <param name="action">tên hành động</param>
        /// <returns>số lượt gọi hành động</returns>
        public static int CheckAccountActionFrequency(string accountName, int totalSecond, string action)
        {
            System.Runtime.Caching.ObjectCache     cache  = System.Runtime.Caching.MemoryCache.Default;
            System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy()
            {
                AbsoluteExpiration = DateTime.Now.AddSeconds(totalSecond)
            };
            object cacheCounter = cache.Get("P" + accountName + "_" + action);

            if (cacheCounter == null)
            {
                cache.Set("P" + accountName + "_" + action, 1, policy);
                return(0);
            }
            cache.Set("P" + accountName + "_" + action, Convert.ToInt32(cacheCounter) + 1, policy);
            return(Convert.ToInt32(cacheCounter));
        }
Пример #17
0
        /// <summary>
        /// Kiểm tra ip thực hiện 1 hành động trong số giây (tự cộng số lượt mỗi lần gọi hàm check)
        /// Không ăn theo tài khoản
        /// </summary>
        /// <param name="totalSecond">Số giây kiểm tra</param>
        /// <param name="action">tên hành động</param>
        /// <returns>số lượt gọi hành động</returns>
        public static int CheckIpPostFrequency(int totalSecond, string action)
        {
            string ip = IPAddressHelper.GetClientIP();

            System.Runtime.Caching.ObjectCache     cache  = System.Runtime.Caching.MemoryCache.Default;
            System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy()
            {
                AbsoluteExpiration = DateTime.Now.AddSeconds(totalSecond)
            };
            object cacheCounter = cache.Get("P" + ip.ToLower() + "_" + action);

            if (cacheCounter == null)
            {
                cache.Set("P" + ip.ToLower() + "_" + action, 1, policy);
                return(0);
            }
            cache.Set("P" + ip.ToLower() + "_" + action, Convert.ToInt32(cacheCounter) + 1, policy);
            return(Convert.ToInt32(cacheCounter));
        }
Пример #18
0
 /// <summary>
 /// 以一个会话标示,初始化本类
 /// </summary>
 /// <param name="sessionId"></param>
 public ServiceSession(string sessionId)
 {
     if (string.IsNullOrEmpty(sessionId))
     {
         throw new InvalidOperationException("会话标识不能为空!");
     }
     this.SessionID  = sessionId;
     keyList         = new List <string>();
     cache           = CacheProviderFactory.GetCacheProvider();
     cacheItemPolicy = new System.Runtime.Caching.CacheItemPolicy()
     {
         SlidingExpiration = new TimeSpan(0, 10, 0),    //距离上次调用10分钟后过期
         RemovedCallback   = args =>
         {
             object obj = args.CacheItem.Value;
             //可记录会话日志
         }
     };
 }
Пример #19
0
        private int CheckIpPostFrequency(int totalSecond, string action)
        {
            string ip = Utils.GetIp();

            System.Runtime.Caching.ObjectCache     cache  = System.Runtime.Caching.MemoryCache.Default;
            System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy()
            {
                AbsoluteExpiration = DateTime.Now.AddSeconds(totalSecond)
            };
            object cacheCounter = cache.Get("Post" + ip.ToLower() + AccountSession.AccountName + "_" + action);

            if (cacheCounter == null)
            {
                cache.Set("Post" + ip.ToLower() + AccountSession.AccountName + "_" + action, 1, policy);
                return(0);
            }
            cache.Set("Post" + ip.ToLower() + AccountSession.AccountName + "_" + action, Convert.ToInt32(cacheCounter) + 1, policy);
            return(Convert.ToInt32(cacheCounter));
        }
Пример #20
0
        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiry">过期时间</param>
        /// <returns></returns>
        public bool Add(string key, object value, TimeSpan?expiry = null)
        {
#if net40
            var cachePolicy = new System.Runtime.Caching.CacheItemPolicy();
            if (expiry.HasValue)
            {
                cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.Add(expiry.Value);
            }
            var item = new System.Runtime.Caching.CacheItem(key, value);
            Cache.Set(item, cachePolicy);
#endif
#if netstandard2_0
            using (var entry = Cache.CreateEntry(key))
            {
                entry.Value = value;
                entry.AbsoluteExpirationRelativeToNow = expiry;
            }
#endif
            return(true);
        }
        public System.Runtime.Caching.CacheItemPolicy Convert(CacheItemPolicy item)
        {
            var result = new System.Runtime.Caching.CacheItemPolicy();

            if (item.AbsoluteExpiration.HasValue)
            {
                result.AbsoluteExpiration = item.AbsoluteExpiration.Value;
            }

            if (item.SlidingExpiration.HasValue)
            {
                result.SlidingExpiration = item.SlidingExpiration.Value;
            }

            if (item.DirectoriesOrFiles != null && item.DirectoriesOrFiles.Any())
            {
                result.ChangeMonitors.Add(new System.Runtime.Caching.HostFileChangeMonitor(item.DirectoriesOrFiles.ToList()));
            }

            return result;
        }
Пример #22
0
        public void Execute(StringScanner s, Env env, out bool b, out object sd)
        {
            b  = false;
            sd = null;
            var key   = s.Scan(@"set.([\w$]*).value\s*", 1);
            var value = s.Scan(".*").TrimToNull();

            var obj = new System.Runtime.Caching.CacheItemPolicy();


            Open.cache.Set(key, value, obj);
            //    var new_key = new key_value { key = key, value = value };

            //var doc=    LiteDB.BsonMapper.Global.ToDocument(typeof(key_value), new_key);

            sd = "OK";// value.Length;

            //      var bools= env.Engine.Upsert("key_value",(doc),BsonType.ObjectId);
            //    var wrrw =System.Linq.Enumerable.ToList(doc.Values)[0].RawValue;
            env.Display.WriteLine($"存储 {key} 值为 {value}");
        }
Пример #23
0
        public System.Runtime.Caching.CacheItemPolicy Convert(CacheItemPolicy item)
        {
            var result = new System.Runtime.Caching.CacheItemPolicy();

            if (item.AbsoluteExpiration.HasValue)
            {
                result.AbsoluteExpiration = item.AbsoluteExpiration.Value;
            }

            if (item.SlidingExpiration.HasValue)
            {
                result.SlidingExpiration = item.SlidingExpiration.Value;
            }

            if (item.DirectoriesOrFiles != null && item.DirectoriesOrFiles.Any())
            {
                result.ChangeMonitors.Add(new System.Runtime.Caching.HostFileChangeMonitor(item.DirectoriesOrFiles.ToList()));
            }

            return(result);
        }
Пример #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:LibWhipLru.Cache.StorageManager"/> class.
        /// A zero or negative value for the negativeCacheItemLifetime results in the negative cache being disabled.
        /// </summary>
        /// <param name="localStorage">Local storage for assets.</param>
        /// <param name="negativeCacheItemLifetime">Negative cache item lifetime.</param>
        /// <param name="reader">Reader.</param>
        /// <param name="writer">Writer.</param>
        public StorageManager(
            AssetLocalStorageLmdbPartitionedLRU localStorage,
            TimeSpan negativeCacheItemLifetime,
            ChattelReader reader,
            ChattelWriter writer
            )
        {
            _localStorage = localStorage ?? throw new ArgumentNullException(nameof(localStorage));
            _assetReader  = reader ?? throw new ArgumentNullException(nameof(reader));
            _assetWriter  = writer ?? throw new ArgumentNullException(nameof(writer));

            if (negativeCacheItemLifetime.TotalSeconds > 0)
            {
                _negativeCache     = System.Runtime.Caching.MemoryCache.Default;
                _negativeCacheLock = new ReaderWriterLockSlim();

                _negativeCachePolicy = new System.Runtime.Caching.CacheItemPolicy {
                    SlidingExpiration = negativeCacheItemLifetime,
                };
            }
        }
Пример #25
0
        /// <summary>
        /// 檢查是否存在快取位址,無則創建
        /// </summary>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="absoluteExpiration"></param>
        /// <param name="slidingExpiration"></param>
        /// <returns></returns>
        private static Container <TValue> GetOrStoreContainer <TValue>(this System.Runtime.Caching.ObjectCache cache, string key, DateTimeOffset absoluteExpiration, TimeSpan slidingExpiration)
        {
            var instance = cache[key];

            if (instance == null)
            {
                lock (cache)
                {
                    instance = cache[key];
                    if (instance == null)
                    {
                        instance = new Container <TValue>();
                        System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy();
                        policy.Priority           = System.Runtime.Caching.CacheItemPriority.Default;
                        policy.AbsoluteExpiration = absoluteExpiration;
                        // policy.SlidingExpiration = slidingExpiration;
                        policy.UpdateCallback = CacheItemRemoved;
                        cache.Set(key, instance, policy);
                    }
                }
            }

            return((Container <TValue>)instance);
        }
Пример #26
0
 public abstract void Set(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null);
Пример #27
0
 public abstract void Set(System.Runtime.Caching.CacheItem item, System.Runtime.Caching.CacheItemPolicy policy);
Пример #28
0
 public abstract object AddOrGetExisting(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null);
Пример #29
0
 public abstract System.Runtime.Caching.CacheItem AddOrGetExisting(System.Runtime.Caching.CacheItem value, System.Runtime.Caching.CacheItemPolicy policy);
Пример #30
0
 public virtual bool Add(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null)
 {
     throw null;
 }
Пример #31
0
 public virtual bool Add(System.Runtime.Caching.CacheItem item, System.Runtime.Caching.CacheItemPolicy policy)
 {
     throw null;
 }
        private void GivenPolicyWithSlidingExpirationOf(TimeSpan expiration)
        {
            var policy = new System.Runtime.Caching.CacheItemPolicy { SlidingExpiration = expiration };

            _cacheItemPolicyConverterMock = new Mock<ICacheItemPolicyConverter>();
            _cacheItemPolicyConverterMock
                .Setup(e => e.Convert(It.IsAny<CacheItemPolicy>()))
                .Returns(policy);

            _cacher = new MemoryCacher(_cacheItemPolicyConverterMock.Object, _cacheItemPriorityMock.Object);
        }
        public override void Run()
        {
            Console.WriteLine();
            Console.WriteLine("Preparing raw data...");
            var random = new Random(DateTime.Now.Millisecond);
            var access = new int[RandomAccessCount];
            var data = new Datum[TOTAL_DATUM_COUNT];
            for (var d = 0; d < data.Length; d++)
            {
                data[d] =
                    new Datum
                    {
                        Id = d + 1,
                        SomePayload = Enumerable.Range(0, 26).Aggregate(new StringBuilder(), (sb, i) => sb.Append('A' + random.Next(26))).ToString()
                    };
            }
            // To be fair, we will access each caching facility with the exact same sequence (of length RandomAccessCount)
            // of datum indices (picked randomly in the range 0...TOTAL_DATUM_COUNT - 1, inclusive)
            // (Depending on the ratio RANDOM_ACCESS_COUNT / TOTAL_DATUM_COUNT,
            // some indices in the range 0...TOTAL_DATUM_COUNT - 1 may or may not ever be returned by the below random.Next(...))
            for (var a = 0; a < access.Length; a++)
            {
                access[a] = random.Next(TOTAL_DATUM_COUNT);
            }
            Console.WriteLine();
            Console.WriteLine("... raw data prepared.");

            Console.WriteLine();
            Console.WriteLine("Preparing caches...");

            var accessPercent = RandomAccessCount / 100;

            IMemoryCache<int, Datum> ourMemCache = new MemoryCache<int, Datum>(TOTAL_DATUM_COUNT / 5);
            ourMemCache.SetPolicy(typeof(MruEvictionPolicy<,>));

            using (var msMemCache = new System.Runtime.Caching.MemoryCache("System.Runtime.Caching.MemoryCache"))
            {
                var msPolicy = new System.Runtime.Caching.CacheItemPolicy();
                msPolicy.Priority = System.Runtime.Caching.CacheItemPriority.Default;

                Console.WriteLine();
                Console.WriteLine("... caches prepared.");

                Console.WriteLine();
                Console.WriteLine("Press ESC to skip, or any other key to start stressing .NET's memory cache.");
                if (Console.ReadKey().KeyChar != 27)
                {
                    Console.Clear();
                    Console.WriteLine();
                    Console.WriteLine("About to stress Microsoft's {0}...", typeof(System.Runtime.Caching.MemoryCache).FullName);
                    Console.WriteLine();
                    Console.WriteLine("Total datum count : {0}", TOTAL_DATUM_COUNT.ToString("0,0"));
                    Console.WriteLine();
                    Console.WriteLine("Number of random accesses to perform : {0}", RandomAccessCount.ToString("0,0"));
                    Console.WriteLine();
                    Console.WriteLine("Press any key (and hang on)...");
                    Console.WriteLine();
                    Console.ReadKey();
                    Console.WriteLine("Time... {0}", DateTime.Now.ToString("HH:mm:ss.fff"));
                    Console.WriteLine();

                    var time1 = Time.Start();
                    var period1 = 0d;
                    for (var a = 0; a < access.Length; a++)
                    {
                        var index = access[a];
                        var datum = data[index];
                        var item = (Datum)msMemCache.AddOrGetExisting(datum.Id.ToString(), datum, msPolicy) ?? datum;
                        if (item.Id != datum.Id || item.SomePayload != datum.SomePayload)
                        {
                            throw new Exception("Ouch. Unexpected item.");
                        }
                        if (a % accessPercent == 0)
                        {
                            Console.Write(".");
                        }
                    }
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("Time... {0}", DateTime.Now.ToString("HH:mm:ss.fff"));
                    Console.WriteLine();
                    Console.WriteLine("Elapsed: {0} ms", (period1 = time1.ElapsedMilliseconds).ToString("0,0"));
                    Console.WriteLine("Latency: {0} ms (avg.)", period1 / RandomAccessCount);
                }
            }
            GC.Collect();

            Console.WriteLine();
            Console.WriteLine("Press ESC to skip, or any other key to start stressing our memory cache.");
            if (Console.ReadKey().KeyChar != 27)
            {
                Console.Clear();
                Console.WriteLine();
                Console.WriteLine("About to stress our System.Runtime.Caching.Generic.MemoryCache...");
                Console.WriteLine();
                Console.WriteLine("Total datum count : {0}", TOTAL_DATUM_COUNT.ToString("0,0"));
                Console.WriteLine();
                Console.WriteLine("Number of random accesses to perform : {0}", RandomAccessCount.ToString("0,0"));
                Console.WriteLine();
                Console.WriteLine("Press any key (and hang on)...");
                Console.WriteLine();
                Console.WriteLine("(# of cache evictions shown in parentheses)...");
                Console.WriteLine();
                Console.ReadKey();
                Console.WriteLine("Time... {0}", DateTime.Now.ToString("HH:mm:ss.fff"));
                Console.WriteLine();

                var evictedCount = 0;
                ourMemCache.Policy.OnEvict =
                    delegate(IManagedCache<int, Datum> source, int key, Datum value, EvictionReason reason)
                    {
                        evictedCount++;
                    };
                var time2 = Time.Start();
                var period2 = 0d;
                var misses = 0;
                for (var a = 0; a < access.Length; a++)
                {
                    var index = access[a];
                    var datum = data[index];
                    var item = ourMemCache.GetOrAdd(datum.Id, (Func<object, Datum>)delegate(object context) { misses++; return datum; });
                    if (item.Id != datum.Id || item.SomePayload != datum.SomePayload)
                    {
                        throw new Exception("Ouch. Unexpected item.");
                    }
                    if (a % accessPercent == 0)
                    {
                        Console.Write("({0})", evictedCount);
                        evictedCount = 0;
                    }
                }
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Time... {0}", DateTime.Now.ToString("HH:mm:ss.fff"));
                Console.WriteLine();
                Console.WriteLine("Elapsed: {0} ms", (period2 = time2.ElapsedMilliseconds).ToString("0,0"));
                Console.WriteLine("Latency: {0} ms (avg.)", period2 / RandomAccessCount);
                Console.WriteLine("Initial cache capacity: {0}", ourMemCache.Capacity.ToString("0,0"));
                Console.WriteLine("Final cache size: {0}", ourMemCache.Count.ToString("0,0"));
                Console.WriteLine("No. cache misses: {0}", misses.ToString("0,0"));
                Console.WriteLine("Cache fill ratio: {0}%", (100 * ourMemCache.Count / ourMemCache.Capacity).ToString(".00"));
            }
        }