Esempio n. 1
0
        public object GetValue(string key, Func <string, Tuple <object, TimeSpan> > valueCreator)
        {
            if (valueCreator == null)
            {
                return(_innerCache.Get(key));
            }

            var result = valueCreator(key);

#if !CORE_CLR
            return(_innerCache.AddOrGetExisting(key, result.Item1, new System.Runtime.Caching.CacheItemPolicy()
            {
                SlidingExpiration = result.Item2,
                RemovedCallback = this.OnRemovedCallback,
            }));
#else
            if (!this.Exists(key))
            {
                var options = new MemoryCacheEntryOptions();
                options.SlidingExpiration = result.Item2;
                options.RegisterPostEvictionCallback(this.OnPostEvictionCallback);

                return(_innerCache.Set(key, result.Item1, options));
            }
            else
            {
                return(_innerCache.Get(key));
            }
#endif
        }
Esempio n. 2
0
        public object GetValue(string key, Func <string, Tuple <object, TimeSpan> > valueCreator)
        {
            if (valueCreator == null)
            {
                return(_innerCache.Get(key));
            }

            var result = valueCreator(key);

            return(_innerCache.AddOrGetExisting(key, result.Item1, new System.Runtime.Caching.CacheItemPolicy()
            {
                SlidingExpiration = result.Item2,
                //UpdateCallback = this.OnUpdateCallback,
                RemovedCallback = this.OnRemovedCallback,
            }));
        }
Esempio n. 3
0
        /// <inheritdoc />
        public T AddOrGetExisting <T>(string key, Func <T> factory, TimeSpan?lifeSpan)
        {
            var objectToAdd         = factory();
            var cacheItemExpiryDate = GetCacheItemExpiryDate(lifeSpan);
            var result = cache.AddOrGetExisting(key, objectToAdd, cacheItemExpiryDate) ?? objectToAdd;

            return((T)result);
        }
 public static T GetOrSet <T>(string key, Func <T> valueFactory, TimeSpan expiry)
 {
     try
     {
         var newValue = new Lazy <T>(valueFactory);
         var oldValue = _memorycache.AddOrGetExisting(key, newValue, DateTimeOffset.UtcNow.Add(expiry)) as Lazy <T>;
         return((oldValue ?? newValue).Value);
     }
     catch
     {
         _memorycache.Remove(key);
         return(default(T));
     }
 }
        private async Task <T> GetOrSetMemory <T>(string key, TimeSpan timespan, Func <Task <T> > valueFactory)
        {
            var newValue = new Lazy <Task <T> >(valueFactory);
            var oldValue = _memorycache.AddOrGetExisting(key, newValue, DateTimeOffset.UtcNow.Add(timespan)) as Lazy <Task <T> >;

            try
            {
                return(await(oldValue ?? newValue).Value.ConfigureAwait(false));
            }
            catch
            {
                _memorycache.Remove(key);
                return(default(T));
            }
        }
Esempio n. 6
0
        public object GetValue(string key, Func <string, CacheEntry> valueCreator)
        {
            if (valueCreator == null)
            {
                return(_innerCache.Get(key));
            }

            var entry = valueCreator(key);

            return(_innerCache.AddOrGetExisting(key, entry.Value, new System.Runtime.Caching.CacheItemPolicy()
            {
                SlidingExpiration = entry.Expiry ?? System.Runtime.Caching.ObjectCache.NoSlidingExpiration,
                //UpdateCallback = this.OnUpdateCallback,
                RemovedCallback = this.OnRemovedCallback,
            }));
        }
Esempio n. 7
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 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"));
            }
        }