Beispiel #1
0
        public static void Main(string[] args)
        {
            // Runs several concurrent threads that access an item that periodically expires and is re-created.
            MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
            string key = "MyKey";

            var options = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMilliseconds(50));

            var tasks = new List<Task>();
            for (int threads = 0; threads < 100; threads++)
            {
                var task = Task.Run(() =>
                {
                    for (int i = 0; i < 110000; i++)
                    {
                        object value;
                        if(!cache.TryGetValue(key, out value))
                        {
                            // Fake expensive object creation.
                            for (int j = 0; j < 1000000; j++)
                            {
                            }

                            cache.Set(key, new object(), options);
                        }
                    }
                });
                tasks.Add(task);
            }

            Console.WriteLine("Running");
            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("Done");
        }
 static LocalCacheService()
 {
     MemoryCache = new MemoryCache((new MemoryCacheOptions
     {
         CompactOnMemoryPressure = true,
     }));
 }
Beispiel #3
0
        public void Main()
        {
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());

            SetKey(cache, "0");

            PriodicallyReadKey(cache, TimeSpan.FromSeconds(1));

            PeriodciallyRemoveKey(cache, TimeSpan.FromSeconds(11));

            PeriodciallySetKey(cache, TimeSpan.FromSeconds(13));

            Console.ReadLine();
            Console.WriteLine("Shutting down");
        }
Beispiel #4
0
 public PhotoController()
 {
     _cache = new MemoryCache(new MemoryCacheOptions { CompactOnMemoryPressure = false, ExpirationScanFrequency = new TimeSpan(0, 0, 30) });
     _cache.Set(_cacheKey, new[]
     {
         new { Thumbnail = "DSC00597_small.jpeg", FullSize = "DSC00597.Jpg", Raw = "DSC00597.ARW" },
         new { Thumbnail = "DSC00601_small.jpeg", FullSize = "DSC00601.Jpg", Raw = "DSC00601.ARW" },
         new { Thumbnail = "DSC00605_small.jpeg", FullSize = "DSC00605.Jpg", Raw = "DSC00605.ARW" },
         new { Thumbnail = "DSC00609_small.jpeg", FullSize = "DSC00609.Jpg", Raw = "DSC00609.ARW" },
         new { Thumbnail = "DSC00615_small.jpeg", FullSize = "DSC00615.Jpg", Raw = "DSC00615.ARW" },
         new { Thumbnail = "DSC00620_small.jpeg", FullSize = "DSC00620.Jpg", Raw = "DSC00620.ARW" },
         new { Thumbnail = "DSC00625_small.jpeg", FullSize = "DSC00625.Jpg", Raw = "DSC00625.ARW" },
         new { Thumbnail = "DSC00629_small.jpeg", FullSize = "DSC00629.Jpg", Raw = "DSC00629.ARW" },
         new { Thumbnail = "DSC00598_small.jpeg", FullSize = "DSC00598.Jpg", Raw = "DSC00598.ARW" },
         new { Thumbnail = "DSC00602_small.jpeg", FullSize = "DSC00602.Jpg", Raw = "DSC00602.ARW" },
         new { Thumbnail = "DSC00606_small.jpeg", FullSize = "DSC00606.Jpg", Raw = "DSC00606.ARW" },
         new { Thumbnail = "DSC00610_small.jpeg", FullSize = "DSC00610.Jpg", Raw = "DSC00610.ARW" },
         new { Thumbnail = "DSC00617_small.jpeg", FullSize = "DSC00617.Jpg", Raw = "DSC00617.ARW" },
         new { Thumbnail = "DSC00621_small.jpeg", FullSize = "DSC00621.Jpg", Raw = "DSC00621.ARW" },
         new { Thumbnail = "DSC00626_small.jpeg", FullSize = "DSC00626.Jpg", Raw = "DSC00626.ARW" },
         new { Thumbnail = "DSC00630_small.jpeg", FullSize = "DSC00630.Jpg", Raw = "DSC00630.ARW" },
         new { Thumbnail = "DSC00599_small.jpeg", FullSize = "DSC00599.Jpg", Raw = "DSC00599.ARW" },
         new { Thumbnail = "DSC00603_small.jpeg", FullSize = "DSC00603.Jpg", Raw = "DSC00603.ARW" },
         new { Thumbnail = "DSC00607_small.jpeg", FullSize = "DSC00607.Jpg", Raw = "DSC00607.ARW" },
         new { Thumbnail = "DSC00611_small.jpeg", FullSize = "DSC00611.Jpg", Raw = "DSC00611.ARW" },
         new { Thumbnail = "DSC00618_small.jpeg", FullSize = "DSC00618.Jpg", Raw = "DSC00618.ARW" },
         new { Thumbnail = "DSC00622_small.jpeg", FullSize = "DSC00622.Jpg", Raw = "DSC00622.ARW" },
         new { Thumbnail = "DSC00627_small.jpeg", FullSize = "DSC00627.Jpg", Raw = "DSC00627.ARW" },
         new { Thumbnail = "DSC00600_small.jpeg", FullSize = "DSC00600.Jpg", Raw = "DSC00600.ARW" },
         new { Thumbnail = "DSC00604_small.jpeg", FullSize = "DSC00604.Jpg", Raw = "DSC00604.ARW" },
         new { Thumbnail = "DSC00608_small.jpeg", FullSize = "DSC00608.Jpg", Raw = "DSC00608.ARW" },
         new { Thumbnail = "DSC00614_small.jpeg", FullSize = "DSC00614.Jpg", Raw = "DSC00614.ARW" },
         new { Thumbnail = "DSC00619_small.jpeg", FullSize = "DSC00619.Jpg", Raw = "DSC00619.ARW" },
         new { Thumbnail = "DSC00623_small.jpeg", FullSize = "DSC00623.Jpg", Raw = "DSC00623.ARW" },
         new { Thumbnail = "DSC00628_small.jpeg", FullSize = "DSC00628.Jpg", Raw = "DSC00628.ARW" },
     });
 }
        public void UpdateCacheEntryOptions_SetsSlidingExpiration_IfExpiresSlidingIsSet()
        {
            // Arrange
            var expiresSliding = TimeSpan.FromSeconds(37);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache)
            {
                ExpiresSliding = expiresSliding
            };

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(new EntryLink());

            // Assert
            Assert.Equal(expiresSliding, cacheEntryOptions.SlidingExpiration);
        }
        public void UpdateCacheEntryOptions_SetsAbsoluteExpiration_IfExpiresAfterIsSet()
        {
            // Arrange
            var expiresAfter = TimeSpan.FromSeconds(42);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache)
            {
                ExpiresAfter = expiresAfter
            };

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(new EntryLink());

            // Assert
            Assert.Equal(expiresAfter, cacheEntryOptions.AbsoluteExpirationRelativeToNow);
        }
        public void UpdateCacheEntryOptions_PrefersAbsoluteExpirationSpecifiedOnEntryLinkOverExpiresOn()
        {
            // Arrange
            var expiresOn1 = DateTimeOffset.UtcNow.AddDays(12);
            var expiresOn2 = DateTimeOffset.UtcNow.AddMinutes(4);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache)
            {
                ExpiresOn = expiresOn1
            };

            var entryLink = new EntryLink();
            entryLink.SetAbsoluteExpiration(expiresOn2);

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(entryLink);

            // Assert
            Assert.Equal(expiresOn2, cacheEntryOptions.AbsoluteExpiration);
        }
        public void UpdateCacheEntryOptions_UsesAbsoluteExpirationSpecifiedOnEntryLink()
        {
            // Arrange
            var expiresOn = DateTimeOffset.UtcNow.AddMinutes(7);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache)
            {
            };

            var entryLink = new EntryLink();
            entryLink.SetAbsoluteExpiration(expiresOn);

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(entryLink);

            // Assert
            Assert.Equal(expiresOn, cacheEntryOptions.AbsoluteExpiration);
        }
        public void UpdateCacheEntryOptions_SetsAbsoluteExpiration_IfExpiresOnIsSet()
        {
            // Arrange
            var expiresOn = DateTimeOffset.UtcNow.AddMinutes(4);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache)
            {
                ExpiresOn = expiresOn
            };

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(new EntryLink());

            // Assert
            Assert.Equal(expiresOn, cacheEntryOptions.AbsoluteExpiration);
        }
        public void UpdateCacheContext_SetsAbsoluteExpiration_IfExpiresOnIsSet()
        {
            // Arrange
            var expiresOn = DateTimeOffset.UtcNow.AddMinutes(4);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheContext = new Mock<ICacheSetContext>(MockBehavior.Strict);
            cacheContext.Setup(c => c.SetAbsoluteExpiration(expiresOn))
                        .Verifiable();
            var cacheTagHelper = new CacheTagHelper
            {
                MemoryCache = cache,
                ExpiresOn = expiresOn
            };

            // Act
            cacheTagHelper.UpdateCacheContext(cacheContext.Object, new EntryLink());

            // Assert
            cacheContext.Verify();
        }
        public void UpdateCacheContext_PrefersAbsoluteExpirationSpecifiedOnEntryLinkOverExpiresOn()
        {
            // Arrange
            var expiresOn1 = DateTimeOffset.UtcNow.AddDays(12);
            var expiresOn2 = DateTimeOffset.UtcNow.AddMinutes(4);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheContext = new Mock<ICacheSetContext>();
            var sequence = new MockSequence();
            cacheContext.InSequence(sequence)
                        .Setup(c => c.SetAbsoluteExpiration(expiresOn1))
                        .Verifiable();

            cacheContext.InSequence(sequence)
                        .Setup(c => c.SetAbsoluteExpiration(expiresOn2))
                        .Verifiable();

            var cacheTagHelper = new CacheTagHelper
            {
                MemoryCache = cache,
                ExpiresOn = expiresOn1
            };

            var entryLink = new EntryLink();
            entryLink.SetAbsoluteExpiration(expiresOn2);

            // Act
            cacheTagHelper.UpdateCacheContext(cacheContext.Object, entryLink);

            // Assert
            cacheContext.Verify();
        }
        public async Task ProcessAsync_UsesExpiresSliding_ToExpireCacheEntryWithSlidingExpiration()
        {
            // Arrange - 1
            var currentTime = new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var id = "unique-id";
            var childContent1 = "original-child-content";
            var clock = new Mock<ISystemClock>();
            clock.SetupGet(p => p.UtcNow)
                 .Returns(() => currentTime);
            var cache = new MemoryCache(new MemoryCacheOptions { Clock = clock.Object });
            var tagHelperContext1 = GetTagHelperContext(id, childContent1);
            var tagHelperOutput1 = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput1.PreContent.SetContent("<cache>");
            tagHelperOutput1.PostContent.SetContent("</cache>");
            var cacheTagHelper1 = new CacheTagHelper(cache)
            {
                ViewContext = GetViewContext(),
                ExpiresSliding = TimeSpan.FromSeconds(30)
            };

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent1, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            currentTime = currentTime.AddSeconds(35);
            var childContent2 = "different-content";
            var tagHelperContext2 = GetTagHelperContext(id, childContent2);
            var tagHelperOutput2 = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput2.PreContent.SetContent("<cache>");
            tagHelperOutput2.PostContent.SetContent("</cache>");
            var cacheTagHelper2 = new CacheTagHelper(cache)
            {
                ViewContext = GetViewContext(),
                ExpiresSliding = TimeSpan.FromSeconds(30)
            };

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent2, tagHelperOutput2.Content.GetContent());
        }
Beispiel #13
0
        private static void ScanForExpiredItems(MemoryCache cache)
        {
            List<CacheEntry> expiredEntries = new List<CacheEntry>();

            cache._entryLock.EnterReadLock();
            try
            {
                var now = cache._clock.UtcNow;
                foreach (var entry in cache._entries.Values)
                {
                    if (entry.CheckExpired(now))
                    {
                        expiredEntries.Add(entry);
                    }
                }
            }
            finally
            {
                cache._entryLock.ExitReadLock();
            }

            cache.RemoveEntries(expiredEntries);
        }
        public void UpdateCacheContext_CopiesTriggersFromEntryLink()
        {
            // Arrange
            var expiresSliding = TimeSpan.FromSeconds(30);
            var expected = new[] { Mock.Of<IExpirationTrigger>(), Mock.Of<IExpirationTrigger>() };
            var triggers = new List<IExpirationTrigger>();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheContext = new Mock<ICacheSetContext>();
            cacheContext.Setup(c => c.SetSlidingExpiration(expiresSliding))
                        .Verifiable();
            cacheContext.Setup(c => c.AddExpirationTrigger(It.IsAny<IExpirationTrigger>()))
                        .Callback<IExpirationTrigger>(triggers.Add)
                        .Verifiable();
            var cacheTagHelper = new CacheTagHelper
            {
                MemoryCache = cache,
                ExpiresSliding = expiresSliding
            };

            var entryLink = new EntryLink();
            entryLink.AddExpirationTriggers(expected);

            // Act
            cacheTagHelper.UpdateCacheContext(cacheContext.Object, entryLink);

            // Assert
            cacheContext.Verify();
            Assert.Equal(expected, triggers);
        }
        public void UpdateCacheContext_SetsCachePreservationPriority()
        {
            // Arrange
            var priority = CachePreservationPriority.High;
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheContext = new Mock<ICacheSetContext>();
            cacheContext.Setup(c => c.SetPriority(priority))
                        .Verifiable();
            var cacheTagHelper = new CacheTagHelper
            {
                MemoryCache = cache,
                Priority = priority
            };

            // Act
            cacheTagHelper.UpdateCacheContext(cacheContext.Object, new EntryLink());

            // Assert
            cacheContext.Verify();
        }
        public void UpdateCacheContext_SetsSlidingExpiration_IfExpiresSlidingIsSet()
        {
            // Arrange
            var expiresSliding = TimeSpan.FromSeconds(37);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheContext = new Mock<ICacheSetContext>();
            cacheContext.Setup(c => c.SetSlidingExpiration(expiresSliding))
                        .Verifiable();
            var cacheTagHelper = new CacheTagHelper
            {
                MemoryCache = cache,
                ExpiresSliding = expiresSliding
            };

            // Act
            cacheTagHelper.UpdateCacheContext(cacheContext.Object, new EntryLink());

            // Assert
            cacheContext.Verify();
        }
        public void UpdateCacheEntryOptions_SetsCachePreservationPriority()
        {
            // Arrange
            var priority = CacheItemPriority.High;
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache)
            {
                Priority = priority
            };

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(new EntryLink());

            // Assert
            Assert.Equal(priority, cacheEntryOptions.Priority);
        }
Beispiel #18
0
        public void Main()
        {
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
            object result;
            string key = "Key";
            object newObject = new object();
            object state = new object();

            // Basic CRUD operations:

            // Create / Overwrite
            result = cache.Set(key, newObject);
            result = cache.Set(key, new object());

            // Retrieve, null if not found
            result = cache.Get(key);

            // Retrieve
            bool found = cache.TryGetValue(key, out result);

            // Delete
            cache.Remove(key);

            // Cache entry configuration:

            // Stays in the cache as long as possible
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove));

            // Automatically remove if not accessed in the given time
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5)));

            // Automatically remove at a certain time
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2)));

            // Automatically remove at a certain time, which is relative to UTC now
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetAbsoluteExpiration(relative: TimeSpan.FromMinutes(10)));

            // Automatically remove if not accessed in the given time
            // Automatically remove at a certain time (if it lives that long)
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(5))
                .SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2)));

            // Callback when evicted
            var options = new MemoryCacheEntryOptions()
                .RegisterPostEvictionCallback(
                (echoKey, value, reason, substate) =>
                {
                    Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                });
            result = cache.Set(key, new object(), options);

            // Remove on token expiration
            var cts = new CancellationTokenSource();
            options = new MemoryCacheEntryOptions()
                .AddExpirationToken(new CancellationChangeToken(cts.Token))
                .RegisterPostEvictionCallback(
                (echoKey, value, reason, substate) =>
                {
                    Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                });
            result = cache.Set(key, new object(), options);

            // Fire the token to see the registered callback being invoked
            cts.Cancel();

            // Expire an entry if the dependent entry expires
            using (var link = cache.CreateLinkingScope())
            {
                cts = new CancellationTokenSource();
                cache.Set("key1", "value1", new MemoryCacheEntryOptions()
                    .AddExpirationToken(new CancellationChangeToken(cts.Token)));

                // expire this entry if the entry with key "key1" expires.
                cache.Set("key2", "value2", new MemoryCacheEntryOptions()
                    .AddEntryLink(link)
                    .RegisterPostEvictionCallback(
                    (echoKey, value, reason, substate) =>
                    {
                        Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                    }));
            }

            // Fire the token to see the registered callback being invoked
            cts.Cancel();
        }
        public void UpdateCacheEntryOptions_CopiesTriggersFromEntryLink()
        {
            // Arrange
            var expiresSliding = TimeSpan.FromSeconds(30);
            var expected = new[] { Mock.Of<IExpirationTrigger>(), Mock.Of<IExpirationTrigger>() };
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache)
            {
                ExpiresSliding = expiresSliding
            };

            var entryLink = new EntryLink();
            entryLink.AddExpirationTriggers(expected);

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(entryLink);

            // Assert
            Assert.Equal(expected, cacheEntryOptions.Triggers.ToArray());
        }
        public void UpdateCacheContext_UsesAbsoluteExpirationSpecifiedOnEntryLink()
        {
            // Arrange
            var expiresOn = DateTimeOffset.UtcNow.AddMinutes(7);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheContext = new Mock<ICacheSetContext>(MockBehavior.Strict);
            cacheContext.Setup(c => c.SetAbsoluteExpiration(expiresOn))
                        .Verifiable();
            var cacheTagHelper = new CacheTagHelper
            {
                MemoryCache = cache
            };

            var entryLink = new EntryLink();
            entryLink.SetAbsoluteExpiration(expiresOn);

            // Act
            cacheTagHelper.UpdateCacheContext(cacheContext.Object, entryLink);

            // Assert
            cacheContext.Verify();
        }
        public async Task ProcessAsync_FlowsEntryLinkThatAllowsAddingTriggersToAddedEntry()
        {
            // Arrange
            var id = "some-id";
            var expectedContent = new DefaultTagHelperContent();
            expectedContent.SetContent("some-content");
            var tokenSource = new CancellationTokenSource();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .AddExpirationTrigger(new CancellationTokenTrigger(tokenSource.Token));
            var tagHelperContext = new TagHelperContext(
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary<object, object>(),
                uniqueId: id,
                getChildContentAsync: () =>
                {
                    TagHelperContent tagHelperContent;
                    if(!cache.TryGetValue("key1", out tagHelperContent))
                    {
                        tagHelperContent = expectedContent;
                        cache.Set("key1", tagHelperContent, cacheEntryOptions);
                    }

                    return Task.FromResult(tagHelperContent);
                });
            var tagHelperOutput = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput.PreContent.SetContent("<cache>");
            tagHelperOutput.PostContent.SetContent("</cache>");
            var cacheTagHelper = new CacheTagHelper(cache)
            {
                ViewContext = GetViewContext(),
            };
            var key = cacheTagHelper.GenerateKey(tagHelperContext);

            // Act - 1
            await cacheTagHelper.ProcessAsync(tagHelperContext, tagHelperOutput);
            TagHelperContent cachedValue;
            var result = cache.TryGetValue(key, out cachedValue);

            // Assert - 1
            Assert.Equal(expectedContent.GetContent(), tagHelperOutput.Content.GetContent());
            Assert.True(result);
            Assert.Equal(expectedContent, cachedValue);

            // Act - 2
            tokenSource.Cancel();
            result = cache.TryGetValue(key, out cachedValue);

            // Assert - 2
            Assert.False(result);
            Assert.Null(cachedValue);
        }
        public async Task ProcessAsync_ReturnsCachedValue_IfVaryByParamIsUnchanged()
        {
            // Arrange - 1
            var id = "unique-id";
            var childContent = "original-child-content";
            var cache = new MemoryCache(new MemoryCacheOptions());
            var tagHelperContext1 = GetTagHelperContext(id, childContent);
            var tagHelperOutput1 = new TagHelperOutput("cache", new TagHelperAttributeList());
            var cacheTagHelper1 = new CacheTagHelper(cache)
            {
                VaryByQuery = "key1,key2",
                ViewContext = GetViewContext(),
            };
            cacheTagHelper1.ViewContext.HttpContext.Request.QueryString = new Http.QueryString(
                "?key1=value1&key2=value2");

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            var tagHelperContext2 = GetTagHelperContext(id, "different-content");
            var tagHelperOutput2 = new TagHelperOutput("cache", new TagHelperAttributeList());
            var cacheTagHelper2 = new CacheTagHelper(cache)
            {
                VaryByQuery = "key1,key2",
                ViewContext = GetViewContext(),
            };
            cacheTagHelper2.ViewContext.HttpContext.Request.QueryString = new Http.QueryString(
                "?key1=value1&key2=value2");

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent, tagHelperOutput2.Content.GetContent());
        }
        public async Task ProcessAsync_RecalculatesValueIfCacheKeyChanges()
        {
            // Arrange - 1
            var id = "unique-id";
            var childContent1 = "original-child-content";
            var cache = new MemoryCache(new MemoryCacheOptions());
            var tagHelperContext1 = GetTagHelperContext(id, childContent1);
            var tagHelperOutput1 = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput1.PreContent.Append("<cache>");
            tagHelperOutput1.PostContent.SetContent("</cache>");
            var cacheTagHelper1 = new CacheTagHelper(cache)
            {
                VaryByCookie = "cookie1,cookie2",
                ViewContext = GetViewContext(),
            };
            cacheTagHelper1.ViewContext.HttpContext.Request.Headers["Cookie"] = "cookie1=value1;cookie2=value2";

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent1, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            var childContent2 = "different-content";
            var tagHelperContext2 = GetTagHelperContext(id, childContent2);
            var tagHelperOutput2 = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput2.PreContent.SetContent("<cache>");
            tagHelperOutput2.PostContent.SetContent("</cache>");
            var cacheTagHelper2 = new CacheTagHelper(cache)
            {
                VaryByCookie = "cookie1,cookie2",
                ViewContext = GetViewContext(),
            };
            cacheTagHelper2.ViewContext.HttpContext.Request.Headers["Cookie"] = "cookie1=value1;cookie2=not-value2";

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent2, tagHelperOutput2.Content.GetContent());
        }
Beispiel #24
0
        public void Main()
        {
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
            object result;
            string key = "Key";
            object newObject = new object();
            object state = new object();

            // Basic CRUD operations:

            // Create / Overwrite
            result = cache.Set(key, newObject);
            result = cache.Set(key, context => new object());
            result = cache.Set(key, state, context => new object());

            // Retrieve, null if not found
            result = cache.Get(key);

            // Retrieve
            bool found = cache.TryGetValue(key, out result);

            // Delete
            cache.Remove(key);

            // Conditional operations:

            // Retrieve / Create when we want to lazily create the object.
            result = cache.GetOrSet(key, context => new object());

            // Retrieve / Create when we want to lazily create the object.
            result = cache.GetOrSet(key, state, context => new object());

            // Cache entry configuration:

            // Stays in the cache as long as possible
            result = cache.GetOrSet(key, state, context =>
            {
                context.SetPriority(CachePreservationPriority.NeverRemove);
                return new object();
            });

            // Automatically remove if not accessed in the given time
            result = cache.GetOrSet(key, state, context =>
            {
                context.SetSlidingExpiration(TimeSpan.FromMinutes(5));
                return new object();
            });

            // Automatically remove at a certain time
            result = cache.GetOrSet(key, state, context =>
            {
                context.SetAbsoluteExpiration(new DateTime(2014, 12, 31));
                // or relative:
                // context.SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
                return new object();
            });

            // Automatically remove if not accessed in the given time
            // Automatically remove at a certain time (if it lives that long)
            result = cache.GetOrSet(key, state, context =>
            {
                context.SetSlidingExpiration(TimeSpan.FromMinutes(5));

                context.SetAbsoluteExpiration(new DateTime(2014, 12, 31));
                // or relative:
                // context.SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
                return new object();
            });

            // Callback when evicted
            result = cache.GetOrSet(key, state, context =>
            {
                context.RegisterPostEvictionCallback((echoKey, value, reason, substate) =>
                    Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason), state: null);
                return new object();
            });

            // Remove on trigger
            var cts = new CancellationTokenSource();
            result = cache.GetOrSet(key, state, context =>
            {
                context.AddExpirationTrigger(new CancellationTokenTrigger(cts.Token));
                return new object();
            });

            result = cache.GetOrSet(key, context =>
            {
                var link = new EntryLink();

                var inner1 = cache.GetOrSet("subkey1", link, subContext =>
                {
                    return "SubValue1";
                });

                string inner2;
                using (link.FlowContext())
                {
                    inner2 = cache.GetOrSet("subkey2", subContext =>
                    {
                        return "SubValue2";
                    });
                }

                context.AddEntryLink(link);

                return inner1 + inner2;
            });
        }