public void ReleaseCache(System.Runtime.Caching.MemoryCache cache)
 {
     if (cache != null)
     {
         cache.Dispose();
     }
 }
Example #2
0
        void IDisposable.Dispose()
        {
            if (_lock != null)
            {
                _lock.EnterWriteLock(); // registry, write lock

                if (_logicCache != null)
                {
                    foreach (var logic in _logicCache.Values)
                    {
                        if (logic != null)
                        {
                            logic.Dispose();
                        }
                    }
                    _logicCache.Clear();
                    _logicCache = null;
                }

                if (_objectCache != null)
                {
                    _objectCache.Dispose();
                    _objectCache = null;
                }

                _lock.ExitWriteLock(); // registry, write unlock

                _lock.Dispose();
                _lock = null;
            }
        }
Example #3
0
        private void InitSystemMemoryCache()
        {
            // If a memory cache was already instanced, and it was not the default, the dispose it
            // after applying the new initialization.
            if (_store != null && _store != SystemMemoryCache.Default)
            {
                _store.Dispose();
            }

            if (Settings.CacheName == new MemoryCacheSettings().CacheName)
            {
                // If the default cache name is used, then refer to the Default memory cache. It is
                // the safest and most efficient way to use that kind of cache.
                _store = SystemMemoryCache.Default;
                return;
            }

            // Otherwise, if a name has been specified, then we need to apply a proper configuration.
            // This way is more dangerous, because it is not easy to choose the right moment to
            // dispose the memory cache.
            _store = new SystemMemoryCache(Settings.CacheName, new NameValueCollection
            {
                { "CacheMemoryLimitMegabytes", Settings.MaxCacheSizeInMB.ToString() }
            });
        }
Example #4
0
 /// <summary>
 /// Delete cache value from key
 /// </summary>
 /// <param name="key"></param>
 public static void Delete(string key)
 {
     System.Runtime.Caching.MemoryCache memoryCache = System.Runtime.Caching.MemoryCache.Default;
     if (memoryCache.Contains(key))
     {
         memoryCache.Remove(key);
     }
 }
		public MemoryCache(string name, ICacheCreator creator)
		{
			if(string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException("name");

			_innerCache = new System.Runtime.Caching.MemoryCache(name);
			_creator = creator;
		}
Example #6
0
        public MemoryCache(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            _cache = new System.Runtime.Caching.MemoryCache(name);
        }
Example #7
0
        public MemoryCache(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException("name");
            }

            _innerCache = new System.Runtime.Caching.MemoryCache(name);
        }
Example #8
0
        /// <exception cref="ArgumentNullException">thrown, if <paramref name="memoryCacheName"/> is null.</exception>
        /// <exception cref="ArgumentException">
        /// thrown, if <paramref name="memoryCacheName"/> is an empty string or its value is equal to
        /// either the value of the public fieled DefaultCacheRegistryName
        /// or "default" (case insensitive) - a reserved name for the default instance of MemoryCache class.
        /// </exception>
        public CyclicCacheRegistry(string memoryCacheName)
        {
            if (String.Compare(DefaultCacheRegistryName, memoryCacheName) == 0)
            {
                throw new ArgumentException("memoryCacheName");
            }

            _objectCache = new System.Runtime.Caching.MemoryCache(memoryCacheName); // throws
            _name        = memoryCacheName;
        }
            public static object Value(string key)
            {
                string NewKey = TransformKey(key);

                System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;
                if (cache.Contains(NewKey))
                {
                    return(cache[NewKey]);
                }
                return(string.Empty);
            }
Example #10
0
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="InitGroup"></param>
 public DBGuiInterface(String InitGroup, DBConnector useDBCon)
 {
     try
     {
         m_DBCon         = useDBCon;
         m_InitGroup     = InitGroup;
         m_SettingsCache = System.Runtime.Caching.MemoryCache.Default;
     }
     catch (Exception ex)
     {
         throw new Exception("Error while creating object", ex);
     }
 }
Example #11
0
        /// <summary>
        ///   Performs application-defined tasks associated with freeing, releasing, or resetting
        ///   unmanaged resources.
        /// </summary>
        /// <param name="disposing">True if it is a managed dispose, false otherwise.</param>
        /// <remarks>
        ///   When called on a cache using <see cref="SystemMemoryCache.Default"/> as store, this
        ///   method does nothing. In fact, it is not safe to dispose the default memory cache instance.
        /// </remarks>
        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                // Nothing to do, we can handle only managed Dispose calls.
                return;
            }

            if (_store != null && _store != SystemMemoryCache.Default)
            {
                _store.Dispose();
                _store = null;
            }
        }
Example #12
0
        public AppCache()
        {
            System.Runtime.Caching.MemoryCache mcache = System.Runtime.Caching.MemoryCache.Default;
            List <AppModel> _cacheapps = mcache.Get(getcachename) as List <AppModel>;

            if (_cacheapps == null)
            {
                _cacheapps = new List <AppModel>();
                bool r = mcache.Add(getcachename, _cacheapps, new DateTimeOffset(DateTime.Now.AddMinutes(expiresminutes)));
                if (!r)
                {
                    throw new Exception("初始化缓存失败。");
                }
            }
            cacheapps = _cacheapps.CloneList();
        }
        private static void AddToCache(IPackageName package, MemoryCache memoryCache)
        {
            var cachedObject = memoryCache[package.Id];

            if (cachedObject != null)
            {
                if (package.Version > ((IPackage)cachedObject).Version)
                {
                    memoryCache[package.Id] = package;
                }
            }
            else
            {
                memoryCache[package.Id] = package;
            }
        }
Example #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
            }
        }
Example #15
0
        public MemoryCache(string name, ICacheCreator creator)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException("name");
            }

            _creator = creator;
            _name    = name;

#if !CORE_CLR
            _innerCache = new System.Runtime.Caching.MemoryCache(name);
#else
            _innerCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
#endif
        }
Example #16
0
        public void TestRunTimeCache()
        {
            var cache = new System.Runtime.Caching.MemoryCache("sys");

            cache.Add("user", new User {
                Name = "Foo"
            }, DateTime.Now.AddDays(1));

            User f = (User)cache.Get("user");

            Assert.Equal("Foo", f.Name);

            f.Name = "Bar";
            var b = (User)cache.Get("user");

            Assert.Equal("Bar", b.Name);
        }
Example #17
0
        public CertCache(ServiceCertType certtype)
        {
            this.certtype = certtype;
            System.Runtime.Caching.MemoryCache mcache = System.Runtime.Caching.MemoryCache.Default;
            List <CertCacheItem> _tempmanagecache     = mcache.Get(cachetypename) as List <CertCacheItem>;

            if (_tempmanagecache == null)
            {
                _tempmanagecache = new List <CertCacheItem>();
                bool r = mcache.Add(cachetypename, _tempmanagecache, new DateTimeOffset(DateTime.Now.AddMinutes(expiresminutes)));
                if (!r)
                {
                    throw new Exception("初始化缓存失败。");
                }
            }
            tempmanagecache = _tempmanagecache.CloneList();
        }
Example #18
0
        private void SetCache()
        {
            System.Runtime.Caching.MemoryCache mcache = System.Runtime.Caching.MemoryCache.Default;
            if (cacheapps == null)
            {
                cacheapps = new List <AppModel>();
            }
            if (mcache.Get(getcachename) != null)
            {
                mcache.Remove(getcachename);
            }

            bool r = mcache.Add(getcachename, cacheapps.CloneList(), new DateTimeOffset(DateTime.Now.AddMinutes(expiresminutes)));

            if (!r)
            {
                mcache = null;
            }
        }
Example #19
0
        private void SetCertCahe()
        {
            System.Runtime.Caching.MemoryCache mcache = System.Runtime.Caching.MemoryCache.Default;
            if (tempmanagecache == null)
            {
                tempmanagecache = new List <CertCacheItem>();
            }
            if (mcache.Get(cachetypename) != null)
            {
                mcache.Remove(cachetypename);
            }

            bool r = mcache.Add(cachetypename, tempmanagecache.CloneList(), new DateTimeOffset(DateTime.Now.AddMinutes(expiresminutes)));

            if (!r)
            {
                mcache = null;
            }
        }
Example #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MemoryCache"/> class.
 /// </summary>
 public MemoryCache()
 {
     _memoryCache = new System.Runtime.Caching.MemoryCache("MemoryCache");
 }
Example #21
0
 /// <summary>
 /// Initialises a new instance of the <see cref="MemoryCache"/> class.
 /// Creates an instance of <see cref="MemoryCache"/> class with the named instance of <see cref="System.Runtime.Caching.MemoryCache"/> />.
 /// </summary>
 public MemoryCache(string name)
 {
     cache = new System.Runtime.Caching.MemoryCache(name);
 }
Example #22
0
 /// <summary>
 /// Initialises a new instance of the <see cref="MemoryCache"/> class.
 /// Creates an instance of <see cref="MemoryCache"/> class with the default instance of <see cref="System.Runtime.Caching.MemoryCache"/> />.
 /// </summary>
 public MemoryCache()
 {
     cache = System.Runtime.Caching.MemoryCache.Default;
 }
Example #23
0
 private CyclicCacheRegistry()
 {
     _objectCache = new System.Runtime.Caching.MemoryCache(DefaultCacheRegistryName);
     _name        = DefaultCacheRegistryName;
 }
 public static void Set(string key, object o, int timeout)
 {
     System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;
     cache.Add(TransformKey(key), o, DateTime.Now.AddMinutes(timeout));
 }
Example #25
0
 public MemoryCacheImpl(MemCache memoryCache)
 {
     _cache = memoryCache;
 }
Example #26
0
        static void Main(string[] args)
        {
            #region PS:这个示例使用了MemoryCache
            //            PS:这个示例使用了MemoryCache,需要使用Nuget安装Polly.Caching.MemoryCache程序包,以及添加System.Runtime.Caching的引用。

            //从运行结果可以看到,虽然三次执行都有结果,但系统只有第一次才需要执行函数,剩下两次都是直接从缓存中获取的结果。

            //系统也提供了多种不同的过期策略:

            //Policy.Cache(memoryCacheProvider, new AbsoluteTtl(DateTimeOffset.Now.Date.AddDays(1)));
            //            Policy.Cache(memoryCacheProvider, new SlidingTtl(TimeSpan.FromMinutes(5)));

            //            对于布式缓存,Polly也有默认的实现,只需要安装Polly.Caching.IdistributedCache程序包即可,它提供了SqlServer和Redis的支持
            #endregion
            var memoryCache         = new System.Runtime.Caching.MemoryCache("cache5566");
            var memoryCacheProvider = new Polly.Caching.MemoryCache.MemoryCacheProvider(memoryCache);

            var cachePolicy = Policy.Cache(memoryCacheProvider, TimeSpan.FromMilliseconds(1000 * 5));

            //Context.ExecutionKey就是cache的key
            var context11 = new Context("cache5566");
            for (int i = 0; i < 3000; i++)
            {
                var cache = cachePolicy.Execute(_ =>
                {
                    Console.WriteLine("===重新获取的值===");
                    return(Guid.NewGuid().ToString());
                }, context11);
                Console.WriteLine(cache);

                System.Threading.Thread.Sleep(500);
            }

            Console.WriteLine("======================");
            Console.ReadKey();


            Policy policy = Policy
                            .Handle <Exception>()
                            .CircuitBreaker(6, TimeSpan.FromSeconds(15));//连续出错6次之后熔断15秒(不会再去尝试执行业务代码)。
            while (true)
            {
                Console.WriteLine("开始Execute");
                try
                {
                    policy.Execute(() => {
                        Console.WriteLine("开始任务");
                        throw new Exception("出错");
                        Console.WriteLine("完成任务");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine("execute出错******");
                }
                System.Threading.Thread.Sleep(500);
            }


            Policy
            .Timeout(3, onTimeout: (context, timespan, task) =>
            {
                Console.WriteLine("超时了,奶奶的!");
            }).Execute(() =>
            {
                System.Threading.Thread.Sleep(5000);
            });



            Policy
            .Handle <Exception>()
            .WaitAndRetry(new[]
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(3)
            }, (exception, timeSpan, context) =>
            {
                Console.WriteLine("dsfdsfds9999999999");
            }).Execute(() => {
                Compute();
                //Console.WriteLine("8888888888888");
            });



            var fallBackPolicy =
                Policy <List <string> >
                .Handle <Exception>()
                .Fallback <List <string> >(new List <string>()
            {
                "@@@@@", "#####"
            });

            var fallBack = fallBackPolicy.Execute(() =>
            {
                return(ThrowException());
            });

            fallBack.ForEach(Item =>
            {
                Console.WriteLine(Item);
            });



            #region MyRegion
            //try
            //{
            //    var politicaWaitAndRetry = Policy
            //        .Handle<DivideByZeroException>()
            //        .WaitAndRetry(new[]
            //        {
            //            TimeSpan.FromSeconds(1),
            //            TimeSpan.FromMinutes(1),
            //            TimeSpan.FromSeconds(5),
            //            TimeSpan.FromSeconds(7)
            //        }, ReportaError);
            //    politicaWaitAndRetry.Execute(() =>
            //    {
            //        ZeroExcepcion();
            //    });
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine($"Executed Failed,Message:({e.Message})");
            //}
            #endregion


            #region 重试次数
            //try
            //{
            //    var retryTwoTimesPolicy =
            //         Policy
            //             .Handle<DivideByZeroException>()
            //             .Or<ArgumentException>()
            //             .Retry(3, (ex, count) =>
            //             {
            //                 Console.WriteLine("执行失败! 重试次数 {0}", count);
            //                 Console.WriteLine("异常来自 {0}", ex.GetType().Name);
            //             });
            //    retryTwoTimesPolicy.Execute(() =>
            //    {
            //        Compute();
            //    });
            //}
            //catch (DivideByZeroException e)
            //{
            //    Console.WriteLine($"0-Excuted Failed,Message: ({e.Message})");
            //}
            //catch(ArgumentException e)
            //{
            //    Console.WriteLine($"1-Excuted Failed,Message: ({e.Message})");
            //}
            #endregion

            Console.ReadKey();
        }
Example #27
0
 public void UpdateCacheSize(long size, System.Runtime.Caching.MemoryCache cache)
 {
     Console.WriteLine("{0}的缓存消耗:{1}", cache.Name, size);
 }
Example #28
0
        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"));
            }
        }
 public static bool Exists(string key)
 {
     System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;
     return(cache.Contains(TransformKey(key)));
 }
Example #30
0
 public CacheManager(string name, NameValueCollection config = null)
 {
     _memoryCache = new System.Runtime.Caching.MemoryCache(name, config);
 }
Example #31
0
 public Cache()
 {
     cache = new System.Runtime.Caching.MemoryCache(Guid.NewGuid().ToString());
 }
        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"));
            }
        }