コード例 #1
0
        public object Get(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("参数[key]不能为空或空字符串");
            }

            CacheItem cacheItem = (CacheItem)inMemoryCache[key];

            if (cacheItem == null)
            {
                return(null);
            }

            lock (inMemoryCache.SyncRoot)
            {
                if (cacheItem.HasExpired())
                {
                    cacheItem.TouchedByUserAction(true);

                    inMemoryCache.Remove(key);

                    return(null);
                }
            }

            cacheItem.TouchedByUserAction(false);
            return(cacheItem.Value);
        }
コード例 #2
0
        public void Clear()
        {
RestartFlushAlgorithm:
            lock (inMemoryCache.SyncRoot)
            {
                foreach (string key in inMemoryCache.Keys)
                {
                    bool      lockWasSuccessful = false;
                    CacheItem itemToRemove      = (CacheItem)inMemoryCache[key];
                    try
                    {
                        if (lockWasSuccessful = Monitor.TryEnter(itemToRemove))
                        {
                            itemToRemove.TouchedByUserAction(true);
                        }
                        else
                        {
                            goto RestartFlushAlgorithm;
                        }
                    }
                    finally
                    {
                        if (lockWasSuccessful)
                        {
                            Monitor.Exit(itemToRemove);
                        }
                    }
                }

                inMemoryCache.Clear();
            }
        }