Beispiel #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);
        }
Beispiel #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);
        }
Beispiel #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);
        }
        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
            }
        }
        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);
                }
            }
        }
Beispiel #6
0
        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));
            }
        }
        public static TItem Set <TItem>(this IMemoryCache cache, object key, TItem value)
        {
            ICacheEntry entry = cache.CreateEntry(key);

            entry.Value = value;
            entry.Dispose();
            return(value);
        }
Beispiel #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);
        }
        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);
        }
        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);
        }
Beispiel #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);
        }
Beispiel #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);
        }
Beispiel #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);
        }
Beispiel #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);
        }
        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);
        }
Beispiel #16
0
 /// <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.
     }
 }
Beispiel #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);
        }
        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);
        }
Beispiel #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));
        }
Beispiel #20
0
 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);
     }
 }
Beispiel #21
0
        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);
        }
Beispiel #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);
        }
Beispiel #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
            }
        }