在控制台应用程序中缓存

时间:2011-09-29 15:31:50

标签: c# caching console

我需要缓存一个通用列表,所以我不必多次查询数据库。在Web应用程序中,我只需将其添加到httpcontext.current.cache。在控制台应用程序中缓存对象的正确方法是什么?

7 个答案:

答案 0 :(得分:15)

将其保留为包含类的实例成员。在Web应用程序中,您无法执行此操作,因为每次请求都会重新创建页面类的对象。

然而,.NET 4.0也有MemoryCache类用于此目的。

答案 1 :(得分:7)

在类级变量中。据推测,在控制台应用程序的main方法中,您实例化至少一个某种对象。在这个对象的类中,您声明了一个类级变量(List<String>或其他),您可以在其中缓存任何需要缓存的内容。

答案 2 :(得分:3)

这是我在控制台中使用的一个非常简单的缓存类,它具有自我清理和易于实现的功能。

用法:

return Cache.Get("MyCacheKey", 30, () => { return new Model.Guide().ChannelListings.BuildChannelList(); });

班级:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Timers;

    namespace MyAppNamespace
    {
        public static class Cache
        {
            private static Timer cleanupTimer = new Timer() { AutoReset = true, Enabled = true, Interval = 60000 };
            private static readonly Dictionary<string, CacheItem> internalCache = new Dictionary<string, CacheItem>();

            static Cache()
            {
                cleanupTimer.Elapsed += Clean;
                cleanupTimer.Start();
            }

            private static void Clean(object sender, ElapsedEventArgs e)
            {
                internalCache.Keys.ToList().ForEach(x => { try { if (internalCache[x].ExpireTime <= e.SignalTime) { Remove(x); } } catch (Exception) { /*swallow it*/ } });
            }

            public static T Get<T>(string key, int expiresMinutes, Func<T> refreshFunction)
            {
                if (internalCache.ContainsKey(key) && internalCache[key].ExpireTime > DateTime.Now)
                {
                    return (T)internalCache[key].Item;
                }

                var result = refreshFunction();

                Set(key, result, expiresMinutes);

                return result;
            }

            public static void Set(string key, object item, int expiresMinutes)
            {
                Remove(key);

                internalCache.Add(key, new CacheItem(item, expiresMinutes));
            }

            public static void Remove(string key)
            {
                if (internalCache.ContainsKey(key))
                {
                    internalCache.Remove(key);
                }
            }

            private struct CacheItem
            {
                public CacheItem(object item, int expiresMinutes)
                    : this()
                {
                    Item = item;
                    ExpireTime = DateTime.Now.AddMinutes(expiresMinutes);
                }

                public object Item { get; private set; }
                public DateTime ExpireTime { get; private set; }
            }
        }

}

答案 3 :(得分:2)

// Consider this psuedo code for using Cache
public DataSet GetMySearchData(string search)
{
    // if it is in my cache already (notice search criteria is the cache key)
    string cacheKey = "Search " + search;
    if (Cache[cacheKey] != null)
    {
        return (DataSet)(Cache[cacheKey]);
    }
    else
    {
        DataSet result = yourDAL.DoSearch(search);
        Cache[cacheKey].Insert(result);  // There are more params needed here...
        return result;
    }
}

参考:How do I cache a dataset to stop round trips to db?

答案 4 :(得分:1)

有很多方法可以实现缓存,具体取决于您的具体操作。通常,您将使用字典来保存缓存的值。这是我对缓存的简单实现,它只在有限的时间内缓存值:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CySoft.Collections
{
    public class Cache<TKey,TValue>
    {
        private readonly Dictionary<TKey, CacheItem> _cache = new Dictionary<TKey, CacheItem>();
        private TimeSpan _maxCachingTime;

        /// <summary>
        /// Creates a cache which holds the cached values for an infinite time.
        /// </summary>
        public Cache()
            : this(TimeSpan.MaxValue)
        {
        }

        /// <summary>
        /// Creates a cache which holds the cached values for a limited time only.
        /// </summary>
        /// <param name="maxCachingTime">Maximum time for which the a value is to be hold in the cache.</param>
        public Cache(TimeSpan maxCachingTime)
        {
            _maxCachingTime = maxCachingTime;
        }

        /// <summary>
        /// Tries to get a value from the cache. If the cache contains the value and the maximum caching time is
        /// not exceeded (if any is defined), then the cached value is returned, else a new value is created.
        /// </summary>
        /// <param name="key">Key of the value to get.</param>
        /// <param name="createValue">Function creating a new value.</param>
        /// <returns>A cached or a new value.</returns>
        public TValue Get(TKey key, Func<TValue> createValue)
        {
            CacheItem cacheItem;
            if (_cache.TryGetValue(key, out cacheItem) && (DateTime.Now - cacheItem.CacheTime) <= _maxCachingTime) {
                return cacheItem.Item;
            }
            TValue value = createValue();
            _cache[key] = new CacheItem(value);
            return value;
        }

        private struct CacheItem
        {
            public CacheItem(TValue item)
                : this()
            {
                Item = item;
                CacheTime = DateTime.Now;
            }

            public TValue Item { get; private set; }
            public DateTime CacheTime { get; private set; }
        }

    }
}

您可以将lambda表达式传递给Get方法,该方法例如从db中检索值。

答案 5 :(得分:0)

答案 6 :(得分:0)

您可以只使用一个简单的词典。使Cache在Web环境中如此特殊的原因在于它持久存在并且范围很广,许多用户都可以访问它。在控制台应用程序中,您没有这些问题。如果您的需求足够简单,可以使用字典或类似结构快速查找从数据库中提取的值。