예제 #1
0
        public async Task <IPage> GetOrCreate(object key, Func <Task <IPage> > createItem)
        {
            IPage cacheEntry;

            if (!m_Cache.TryGetValue(key, out cacheEntry))
            {
                SemaphoreSlim mylock = m_Locks.GetOrAdd(key, k => new SemaphoreSlim(1, 1));

                await mylock.WaitAsync();

                try
                {
                    if (!m_Cache.TryGetValue(key, out cacheEntry))
                    {
                        cacheEntry = await createItem();

                        m_Cache.Set(key, cacheEntry);
                    }
                }
                finally
                {
                    mylock.Release();
                }
            }
            return(cacheEntry);
        }
예제 #2
0
        public bool Add(string key, object value, DateTimeOffset absExpiration)
        {
            Delete(key);

            var newCacheEntry = _memoryCache.CreateEntry(key);

            newCacheEntry.Value = value;
            newCacheEntry.AbsoluteExpiration = absExpiration;

            return(_memoryCache.TryGetValue(key, out _));
        }
예제 #3
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");
        }
예제 #4
0
 /// <summary>
 /// 验证缓存项是否存在
 /// </summary>
 /// <param name="key">缓存Key</param>
 /// <returns></returns>
 public static bool Exists(string key)
 {
     if (key == null)
     {
         throw new ArgumentNullException(nameof(key));
     }
     return(Cache.TryGetValue(key, out _));
 }
예제 #5
0
 /// <inheritdoc />
 public override async Task <T> GetAsync <T>(string key)
 {
     if (!_memoryCache.TryGetValue <T>(key, out T value))
     {
         return(default(T));
     }
     return(await Task.FromResult(value));
 }
예제 #6
0
        public void TestMemoryObject2()
        {
            var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());

            var entry = cache.CreateEntry("user");

            entry.Value = new User {
                Name = "Foo"
            };


            cache.TryGetValue("user", out User f);
            Assert.Equal("Foo", f.Name);

            f.Name = "Bar";
            cache.TryGetValue("user", out User b);
            Assert.Equal("Bar", b.Name);
        }
예제 #7
0
        public string getLocalPathForURL(string url, string name)
        {
            string localPath = null;

            if (memCache.TryGetValue(name, out localPath))
            {
                return(Path.Combine(specificFolder, localPath));
            }
            memCache.Set(name, name);

            return(null);
        }
예제 #8
0
    public TItem GetOrCreate(object key, Func <TItem> createItem)
    {
        bool isCache = true;

        if (!_cache.TryGetValue(key, out TItem cacheEntry))// Look for cache key.
        {
            SemaphoreSlim mylock = _locks.GetOrAdd(key, k => new SemaphoreSlim(1, 1));

            mylock.Wait();
            try
            {
                if (!_cache.TryGetValue(key, out cacheEntry))
                {
                    // Key not in cache, so get data.
                    isCache    = false;
                    cacheEntry = createItem();
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                                            .SetSize(1) //Size amount
                                                        //Priority on removing when reaching size limit (memory pressure)
                                            .SetPriority(Microsoft.Extensions.Caching.Memory.CacheItemPriority.Low)
                                                        // Keep in cache for this time, reset time if accessed.
                                            .SetSlidingExpiration(TimeSpan.FromSeconds(4))
                                                        // Remove from cache after this time, regardless of sliding expiration
                                            .SetAbsoluteExpiration(TimeSpan.FromSeconds(10));

                    _cache.Set(key, cacheEntry, cacheEntryOptions);
                }
            }
            finally
            {
                mylock.Release();
            }
        }
        if (isCache)
        {
            logger.Info($"Cache : {cacheEntry.ToString()}");
        }
        return(cacheEntry);
    }
예제 #9
0
        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()
                .AddExpirationToken(new CancellationChangeToken(tokenSource.Token));
            var tagHelperContext = new TagHelperContext(
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary<object, object>(),
                uniqueId: id);
            var tagHelperOutput = new TagHelperOutput(
                "cache",
                new TagHelperAttributeList { { "attr", "value" } },
                getChildContentAsync: useCachedResult =>
                {
                    TagHelperContent tagHelperContent;
                    if (!cache.TryGetValue("key1", out tagHelperContent))
                    {
                        tagHelperContent = expectedContent;
                        cache.Set("key1", tagHelperContent, cacheEntryOptions);
                    }

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

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

            // Assert - 1
            Assert.Equal("HtmlEncode[[some-content]]", tagHelperOutput.Content.GetContent());
            Assert.True(result);

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

            // Assert - 2
            Assert.False(result);
            Assert.Null(cachedValue);
        }
예제 #10
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();
        }