微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何创建一个缓存对象的类?

我在c#中是泛型的,我正在尝试创建一个存储,我的程序的其他部分可以要求模型对象.
这个想法是,如果我的缓存类有对象,它会检查它的日期并返回它,如果对象不是大于10分钟.
如果大于10分钟,它将从服务器在线下载更新的模型.
它没有对象是下载它并返回它.

我有一些问题配对我的对象与一个DateTime,使其全部通用.

// model
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();

        Cache c = new Cache();

        p = c.Get<Person>(p);
    }
}

public class Cache
{
    struct Datedobject<T>
    {
        public DateTime Time { get; set; }
        public T Obj { get; set; }
    }

    List<Datedobject<T>> objects;

    public Cache() 
    {
        objects = new List<Datedobject<T>>();
    }

    public T Get<T>(T obj)
    {
        bool found = false;

        // search to see if the object is stored
        foreach(var elem in objects)
            if( elem.ToString().Equals(obj.ToString() ) )
            {
                // the object is found
                found = true;

                // check to see if it is fresh
                TimeSpan sp = DateTime.Now - elem.Time;

                if( sp.TotalMinutes <= 10 )
                    return elem;
            }


        // object was not found or out of date

        // download object from server
        var ret = JsonConvert.DeserializeObject<T>("DOWNLOADED JSON STRING");

        if( found )
        {
            // redate the object and replace it in list
            foreach(var elem in objects)
                if( elem.Obj.ToString().Equals(obj.ToString() ) )
                {
                    elem.Obj = ret;
                    elem.Time = DateTime.Now;
                }
        }
        else
        {
            // add the object to the list
            objects.Add( new Datedobject<T>() { Time = DateTime.Now,Obj = ret });                
        }

        return ret;
    }
}

解决方法

查看作为.NET框架 http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx的一部分可用的内存缓存类

您将需要添加System.RunTime.Caching程序集作为您的应用程序的引用.以下是一个帮助类,用于添加项目并将其从缓存中删除.

using System;
using System.Runtime.Caching;

public static class CacheHelper
{
    public static void Savetocache(string cacheKey,object savedItem,DateTime absoluteExpiration)
    {
        MemoryCache.Default.Add(cacheKey,savedItem,absoluteExpiration);
    }

    public static T GetFromCache<T>(string cacheKey) where T : class
    {
        return MemoryCache.Default[cacheKey] as T;
    }

    public static void RemoveFromCache(string cacheKey)
    {
        MemoryCache.Default.Remove(cacheKey);
    }

    public static bool IsIncache(string cacheKey)
    {
        return MemoryCache.Default[cacheKey] != null;
    }
}

关于这一点的好处是它是线程安全的,它会自动为您自动过期缓存.所以基本上所有你需要做的是检查从MemoryCache获取一个项目是否为null.请注意,MemoryCache仅在.NET 4.0中可用

如果您的应用程序是Web应用程序,则使用System.Web.Caching而不是MemoryCache. System.Web.Caching自.NET 1.1以来一直可用,并且没有额外的参考,您必须添加到您的项目.为网络提供相同的助手类.

using System.Web;

public static class CacheHelper
{
    public static void Savetocache(string cacheKey,DateTime absoluteExpiration)
    {
        if (IsIncache(cacheKey))
        {
            HttpContext.Current.Cache.Remove(cacheKey);
        }

        HttpContext.Current.Cache.Add(cacheKey,null,System.Web.Caching.Cache.NoAbsoluteExpiration,new TimeSpan(0,10,0),System.Web.Caching.CacheItemPriority.Default,null);
    }

    public static T GetFromCache<T>(string cacheKey) where T : class
    {
        return HttpContext.Current.Cache[cacheKey] as T;
    }

    public static void RemoveFromCache(string cacheKey)
    {
        HttpContext.Current.Cache.Remove(cacheKey);
    }

    public static bool IsIncache(string cacheKey)
    {
        return HttpContext.Current.Cache[cacheKey] != null;
    }
}

还有其他缓存过期策略可以用于这两种模式,例如基于文件路径的缓存,以便当文件更改缓存自动过期时,sql缓存依赖性(定期轮询sql Server for改变),滑动过期或你可以建立自己的.他们真的很方便.

原文地址:https://www.jb51.cc/csharp/94882.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐