Caching in a console application

2019-02-08 05:00发布

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?

7条回答
smile是对你的礼貌
2楼-- · 2019-02-08 05:04

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-08 05:10

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.

查看更多
Rolldiameter
5楼-- · 2019-02-08 05:17
// 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?

查看更多
Ridiculous、
6楼-- · 2019-02-08 05:19

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.

查看更多
干净又极端
7楼-- · 2019-02-08 05:19

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.

查看更多
登录 后发表回答