Tom Squires
Tom Squires

Reputation: 9286

Caching in a console application

I need to cache a generic list so I dont have to query the databse multiple times. In a web application I would just add it to the httpcontext.current.cache . What is the proper way to cache objects in console applications?

Upvotes: 20

Views: 21185

Answers (7)

AndrewD
AndrewD

Reputation: 41

Here is a very simple cache class I use in consoles that has self clean up and easy implementation.

The Usage:

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

The Class:

    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; }
            }
        }

}

Upvotes: 4

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

There a many ways to implement caches, depending of what exactly you are doing. Usually you will be using a dictionary to hold cached values. Here is my simple implementation of a cache, which caches values only for a limited time:

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; }
        }

    }
}

You can pass a lambda expression to the Get method, which retrieves values from a db for instance.

Upvotes: 1

Daniel S
Daniel S

Reputation: 11

You might be able to just use a simple Dictionary. The thing that makes the Cache so special in the web environment is that it persists and is scoped in such a way that many users can access it. In a console app, you don't have those issues. If your needs are simple enough, the dictionary or similar structures can be used to quickly lookup values you pull out of a database.

Upvotes: 1

Dariusz Tarczynski
Dariusz Tarczynski

Reputation: 16711

Use Singleton Pattern.

http://msdn.microsoft.com/en-us/library/ff650316.aspx

Upvotes: 0

MusiGenesis
MusiGenesis

Reputation: 75296

In a class-level variable. Presumably, in the main method of your console app you instantiate at least one object of some sort. In this object's class, you declare a class-level variable (a List<String> or whatever) in which you cache whatever needs caching.

Upvotes: 7

Scorpion
Scorpion

Reputation: 4585

// 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;
    }
}

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

Upvotes: 2

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

Keep it as instance member of the containing class. In web app you can't do this since page class's object is recreated on every request.

However .NET 4.0 also has MemoryCache class for this purpose.

Upvotes: 16

Related Questions