コード例 #1
0
        public async Task <T> Get <T>(string key, TimeSpan expireIn, Func <Task <T> > method)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            var result = CacheExtensions.Get(this._cache, key);

            if (result != null)
            {
                return((T)result);
            }

            var keyLock = _locks.GetOrAdd(key, x => new SemaphoreSlim(1));
            await keyLock.WaitAsync();

            try
            {
                result = CacheExtensions.Get(this._cache, key);
                if (result != null)
                {
                    return((T)result);
                }

                var cacheItemPolicy = new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = new DateTimeOffset(DateTime.Now.Add(expireIn))
                };
                result = await method();

                if (result != null)
                {
                    CacheExtensions.Set(this._cache, key, result, cacheItemPolicy);
                }
            }
            finally
            {
                keyLock.Release();
            }

            return((T)(result ?? default(T)));
        }
コード例 #2
0
 public PersonModel GetPersonCache(string key)
 {
     Console.WriteLine("Person data from cache");
     return((PersonModel)CacheExtensions.Get(Cache, key));
 }
コード例 #3
0
 public List <PersonModel> GetPeopleCache(string lastNameKey)
 {
     Console.WriteLine("People data with last name from cache");
     return((List <PersonModel>)CacheExtensions.Get(Cache, lastNameKey));
 }