コード例 #1
0
        public bool Set <T>(string key, T value, TimeSpan expiresIn)
        {
            if (string.IsNullOrEmpty(key))
            {
                return(false);
            }

            _memoryCacheLock.EnterWriteLock();
            ICacheEntry entry = null;

            try
            {
                entry = Cache.CreateEntry(key);
                entry.AbsoluteExpirationRelativeToNow = expiresIn;

                entry.Value = value;

                _keys.Add(key);
            }
            finally
            {
                if (entry != null)
                {
                    entry.Dispose();
                }
                _memoryCacheLock.ExitWriteLock();
            }

            return(true);
        }
コード例 #2
0
        public bool Set <T>(string key, T value, DateTime expiresAt)
        {
            if (string.IsNullOrEmpty(key) && expiresAt > DateTime.Now)
            {
                return(false);
            }

            _memoryCacheLock.EnterWriteLock();
            ICacheEntry entry = null;

            try
            {
                entry = Cache.CreateEntry(key);
                entry.AbsoluteExpiration = expiresAt;
                entry.Value = value;

                _keys.Add(key);
            }
            finally
            {
                if (entry != null)
                {
                    entry.Dispose();
                }
                _memoryCacheLock.ExitWriteLock();
            }

            return(true);
        }
コード例 #3
0
        public bool Set <T>(string key, T value)
        {
            if (string.IsNullOrEmpty(key))
            {
                return(false);
            }

            _memoryCacheLock.EnterWriteLock();
            ICacheEntry entry = null;

            try
            {
                entry       = Cache.CreateEntry(key);
                entry.Value = value;
                _keys.Add(key);
            }
            finally
            {
                if (entry != null)
                {
                    entry.Dispose();
                }
                _memoryCacheLock.ExitWriteLock();
            }

            return(true);
        }
コード例 #4
0
        public void DisposingCacheEntryReleasesScope(bool trackLinkedCacheEntries)
        {
            object GetScope(ICacheEntry entry)
            {
                return(entry.GetType()
                       .GetField("_previous", BindingFlags.NonPublic | BindingFlags.Instance)
                       .GetValue(entry));
            }

            var cache = CreateCache(trackLinkedCacheEntries);

            ICacheEntry first = cache.CreateEntry("myKey1");

            Assert.Null(GetScope(first)); // it's the first entry, so it has no previous cache entry set

            ICacheEntry second = cache.CreateEntry("myKey2");

            if (trackLinkedCacheEntries)
            {
                Assert.NotNull(GetScope(second));     // it's not first, so it has previous set
                Assert.Same(first, GetScope(second)); // second.previous is set to first

                second.Dispose();
                Assert.Null(GetScope(second));
                first.Dispose();
                Assert.Null(GetScope(first));
            }
            else
            {
                Assert.Null(GetScope(second)); // tracking not enabled, the scope is null
            }
        }
コード例 #5
0
        Task <Song> GenerateCacheEntry(ICacheEntry cacheEntry, uint songID, CancellationToken cancellation)
        {
            lock (cacheEntry) {
                if (cacheEntry.Value is Task <Song> generating)
                {
                    return(generating);
                }
                else
                {
                    cacheEntry.SetSlidingExpiration(TimeSpan.FromHours(24));
                    Task <Song> result = this.FetchOrGenerateSong(songID, cancellation);
                    cacheEntry.SetAbsoluteExpiration(TimeSpan.FromDays(7));
                    cacheEntry.Value = result;
                    cacheEntry.Dispose();
                    result.ContinueWith(songTask => {
                        if (!songTask.IsCompletedSuccessfully)
                        {
                            return;
                        }

                        Song song = songTask.Result;
                        cacheEntry.SetSize(
                            song.Title?.Length + song.Lyrics?.Length +
                            song.GeneratorError?.Length ?? 64);
                    });
                    return(result);
                }
            }
        }
コード例 #6
0
ファイル: CacheManager.cs プロジェクト: azgas/plato
        async Task WriteToCache <T>(ICacheEntry entry, string key, T obj)
        {
            try
            {
                if (!UseDistributedCache)
                {
                    entry.SetOptions(new MemoryCacheEntryOptions()
                    {
                        AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds)
                    });

                    // Set expiration tokens
                    entry.ExpirationTokens.Add(_cacheDependency.GetToken(key));
                    entry.SetValue(obj);
                    // need to manually call dispose instead of having a using
                    // statement in case the factory passed in throws, in which case we
                    // do not want to add the entry to the cache
                    entry.Dispose();

                    //_memoryCache.Set(entry.Key.ToString(), obj, DateTimeOffset.UtcNow.AddSeconds(expirationInSeconds));
                    return;
                }
                var toStore = JsonConvert.SerializeObject(obj);
                await _distributedCache.SetAsync(key, Encoding.UTF8.GetBytes(toStore), new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds)
                });
            }
            catch
            {
                // DistributedCache storage failed. Fail over to MemoryCache.

                entry.SetOptions(new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds)
                });

                // Set expiration tokens
                entry.ExpirationTokens.Add(_cacheDependency.GetToken(key));
                entry.SetValue(obj);
                // need to manually call dispose instead of having a using
                // statement in case the factory passed in throws, in which case we
                // do not want to add the entry to the cache
                entry.Dispose();
                //_memoryCache.Set(key, obj, DateTimeOffset.UtcNow.AddSeconds(expirationInSeconds));
            }
        }
コード例 #7
0
        public static TItem Set <TItem>(this IMemoryCache cache, object key, TItem value)
        {
            ICacheEntry entry = cache.CreateEntry(key);

            entry.Value = value;
            entry.Dispose();
            return(value);
        }
コード例 #8
0
        public static T Set <T>(this ICustomCache cache, object key, T value)
        {
            ICacheEntry entry = cache.CreateEntry(key);

            entry.Value = value;
            entry.Dispose();

            return(value);
        }
コード例 #9
0
        public static TItem Set <TItem>(this IMemoryCache cache, object key, TItem value, TimeSpan absoluteExpirationRelativeToNow)
        {
            ICacheEntry entry    = cache.CreateEntry(key);
            TimeSpan?   nullable = absoluteExpirationRelativeToNow;

            entry.AbsoluteExpirationRelativeToNow = nullable;
            entry.Value = value;
            entry.Dispose();
            return(value);
        }
コード例 #10
0
        public static TItem Set <TItem>(this IMemoryCache cache, object key, TItem value, DateTimeOffset absoluteExpiration)
        {
            ICacheEntry    entry    = cache.CreateEntry(key);
            DateTimeOffset?nullable = absoluteExpiration;

            entry.AbsoluteExpiration = nullable;
            entry.Value = value;
            entry.Dispose();
            return(value);
        }
コード例 #11
0
        public static TItem Set <TItem>(this IMemoryCache cache, object key, TItem value, IChangeToken expirationToken)
        {
            ICacheEntry entry = cache.CreateEntry(key);

            entry.AddExpirationToken(expirationToken);
            entry.Value = value;
            entry.Dispose();

            return(value);
        }
コード例 #12
0
        public static T Set <T>(this ICustomCache cache, object key, T value, TimeSpan absoluteExpirationRelativeToNow)
        {
            ICacheEntry entry = cache.CreateEntry(key);

            entry.AbsoluteExpirationRelativeToNow = absoluteExpirationRelativeToNow;
            entry.Value = value;
            entry.Dispose();

            return(value);
        }
コード例 #13
0
        public static T Set <T>(this ICustomCache cache, object key, T value, DateTimeOffset absoluteExpiration)
        {
            ICacheEntry entry = cache.CreateEntry(key);

            entry.AbsoluteExpiration = absoluteExpiration;
            entry.Value = value;
            entry.Dispose();

            return(value);
        }
コード例 #14
0
        public static TItem GetOrCreate <TItem>(this ICustomCache cache, object key, Func <ICacheEntry, TItem> factory)
        {
            if (!cache.TryGetValue(key, out object result))
            {
                ICacheEntry entry = cache.CreateEntry(key);
                result = factory(entry);
                entry.SetValue(result);
                entry.Dispose();
            }

            return((TItem)result);
        }
コード例 #15
0
        private static TItem GetOrCreate <TItem>(this IMemoryCache cache, object key, Func <ICacheEntry, TItem> factory)
        {
            object obj;

            if (!cache.TryGetValue(key, out obj))
            {
                ICacheEntry entry = cache.CreateEntry(key);
                obj = (object)factory(entry);
                entry.SetValue(obj);
                entry.Dispose();
            }
            return((TItem)obj);
        }
コード例 #16
0
ファイル: CacheData.cs プロジェクト: terryzamal/DotStd
 /// <summary>
 /// Store/replace some object in the cache. Assume it isn't already here??
 /// </summary>
 public static void Set(string cacheKey, object value, int decaySec = 10 *kSecond)
 {
     // obj CANT be null, even though it might make sense.
     if (value == null)
     {
         return;
     }
     lock (_cacheKeys)
     {
         ICacheEntry entry = CreateEntry(cacheKey);
         entry.Value = value;
         entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(decaySec);
         entry.Dispose();    // This is what actually adds it to the cache. Weird.
     }
 }
コード例 #17
0
        public static TItem GetOrCreate <TItem>(this IMemoryCache cache, object key, Func <ICacheEntry, TItem> factory)
        {
            if (!cache.TryGetValue(key, out object result))
            {
                ICacheEntry entry = cache.CreateEntry(key);
                result = factory(entry);
                entry.SetValue(result);
                // need to manually call dispose instead of having a using
                // in case the factory passed in throws, in which case we
                // do not want to add the entry to the cache
                entry.Dispose();
            }

            return((TItem)result);
        }
コード例 #18
0
        public static async Task <TItem> GetOrCreateAsync <TItem>(this IMemoryCache cache, object key, Func <ICacheEntry, Task <TItem> > factory)
        {
            object obj;

            if (!cache.TryGetValue(key, out obj))
            {
                ICacheEntry entry = cache.CreateEntry(key);
                obj = await factory(entry);

                entry.SetValue(obj);
                entry.Dispose();
                entry = null;
            }

            return((TItem)obj);
        }
コード例 #19
0
        public void DisposingCacheEntryReleasesScope()
        {
            object GetScope(ICacheEntry entry)
            {
                return(entry.GetType()
                       .GetField("_scope", BindingFlags.NonPublic | BindingFlags.Instance)
                       .GetValue(entry));
            }

            var cache = CreateCache();

            ICacheEntry entry = cache.CreateEntry("myKey");

            Assert.NotNull(GetScope(entry));

            entry.Dispose();
            Assert.Null(GetScope(entry));
        }
コード例 #20
0
ファイル: CacheData.cs プロジェクト: terryzamal/DotStd
 public static T GetOrCreate <T>(string cacheKey, Func <string, T> factory)
 {
     lock (_cacheKeys)
     {
         if (!TryGetValue(cacheKey, out var value))
         {
             // Debug.Assert(!_cacheKeys.Contains(cacheKey));
             ICacheEntry entry = CreateEntry(cacheKey);
             value       = factory(cacheKey);
             entry.Value = value;
             entry.Dispose();    // This is what actually adds it to the cache. Weird.
         }
         else
         {
             // Debug.Assert(_cacheKeys.Contains(cacheKey));
         }
         return((T)value);
     }
 }
コード例 #21
0
ファイル: CacheData.cs プロジェクト: terryzamal/DotStd
        public static async Task <T> GetOrCreateAsync <T>(string cacheKey, Func <string, Task <T> > factory)
        {
            // async version of GetOrCreate

            if (!TryGetValue(cacheKey, out object value))
            {
                value = await factory(cacheKey);        // NOT thread locked. but safe-ish.

                lock (_cacheKeys)
                {
                    // Debug.Assert(!_cacheKeys.Contains(cacheKey));
                    ICacheEntry entry = CreateEntry(cacheKey);
                    entry.Value = value;
                    entry.Dispose();    // This is what actually adds it to the cache. Weird.
                }
            }
            else
            {
                // Debug.Assert(_cacheKeys.Contains(cacheKey));
            }
            return((T)value);
        }
コード例 #22
0
        public bool Set <T>(string key, T value, CacheEntryOptions options)
        {
            if (string.IsNullOrEmpty(key))
            {
                return(false);
            }

            _memoryCacheLock.EnterWriteLock();
            ICacheEntry entry = null;

            try
            {
                entry = Cache.CreateEntry(key);

                entry.AbsoluteExpiration = options.AbsoluteExpiration;
                entry.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow;
                entry.SlidingExpiration = options.SlidingExpiration;
                if (options.NeverRemove)
                {
                    entry.Priority = CacheItemPriority.NeverRemove;
                }

                entry.Value = value;

                _keys.Add(key);
            }
            finally
            {
                if (entry != null)
                {
                    entry.Dispose();
                }
                _memoryCacheLock.ExitWriteLock();
            }

            return(true);
        }
コード例 #23
0
        public void DisposingCacheEntryReleasesScope(bool trackLinkedCacheEntries)
        {
            object GetScope(ICacheEntry entry)
            {
                // Use Type.GetType so that trimming can know what type we operate on
                Type cacheEntryType = Type.GetType("Microsoft.Extensions.Caching.Memory.CacheEntry, Microsoft.Extensions.Caching.Memory");

                Assert.Equal(cacheEntryType, entry.GetType());
                return(cacheEntryType
                       .GetField("_previous", BindingFlags.NonPublic | BindingFlags.Instance)
                       .GetValue(entry));
            }

            var cache = CreateCache(trackLinkedCacheEntries);

            ICacheEntry first = cache.CreateEntry("myKey1");

            Assert.Null(GetScope(first)); // it's the first entry, so it has no previous cache entry set

            ICacheEntry second = cache.CreateEntry("myKey2");

            if (trackLinkedCacheEntries)
            {
                Assert.NotNull(GetScope(second));     // it's not first, so it has previous set
                Assert.Same(first, GetScope(second)); // second.previous is set to first

                second.Dispose();
                Assert.Null(GetScope(second));
                first.Dispose();
                Assert.Null(GetScope(first));
            }
            else
            {
                Assert.Null(GetScope(second)); // tracking not enabled, the scope is null
            }
        }