加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:43:22 所属栏目:百科 来源:网络整理
导读:我在c#中是泛型的,我正在尝试创建一个存储,我的程序的其他部分可以要求模型对象. 这个想法是,如果我的缓存类有对象,它会检查它的日期并返回它,如果对象不是大于10分钟. 如果大于10分钟,它将从服务器在线下载更新的模型. 它没有对象是下载它并返回它. 但我有
我在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改变),滑动过期或你可以建立自己的.他们真的很方便.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读