我怎样才能创建缓存对象的类? [英] How can I create a class that caches objects?

查看:110
本文介绍了我怎样才能创建缓存对象的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林新在C#泛型,我试图创建一个存储我的程序的其他部分可以要求模型对象。
当时的想法是,如果我的缓存类有对象,它会检查它的日期,如果对象是年龄不那么10分返回。
如果是旧的,然后10分钟,它从服务器下载一个更新的模型在线。
它它不具备的对象是下载它并返回它。



但我有我的配对对象有日期时间,makeing这一切的一些问题通用的。

  //模型
公共类Person
{
公共字符串名称{;组; }
公众诠释年龄{搞定;组; }
}

类节目
{
静态无效的主要(字串[] args)
{
者P =新的Person() ;

缓存C =新高速缓存();

p值= c.Get&所述;人>(p)的;
}
}

公共类缓存
{
结构DatedObject< T>
{
公众的DateTime时间{搞定;组; }
公共牛逼的OBJ {搞定;组; }
}

名单,LT; D​​atedObject< T>>物体;

公共缓存()
{
=物体新的List< D​​atedObject< T>>();
}

公众吨得到< T>(T OBJ)
{
布尔发现= FALSE;

//搜索,以查看是否该对象被存储
的foreach(在对象变种ELEM)
如果(elem.ToString()。等于(obj.ToString()))
{
//找到对象
发现= TRUE;

//检查,看看是否是新鲜
时间跨度SP = DateTime.Now - elem.Time;

如果(sp.TotalMinutes< = 10)
返回ELEM;
}


//未找到对象或缩小服务器
VAR RET = JsonConvert日期

//下载的对象。 DeserializeObject< T>(已下载的JSON字符串);

如果(找到)
{
// redate对象,并(在对象VAR ELEM)的列表
的foreach替换
如果(ELEM。 obj.ToString()等于(obj.ToString()))
{
elem.Obj = RET。
elem.Time = DateTime.Now;
}
}
,否则
{
//对象添加到列表中
objects.Add(新DatedObject< T>(){时间= DateTime.Now,OBJ = RET});
}

返回RET;
}
}


解决方案

检查出可用的内存缓存类作为.NET Framework的一部分的http:// MSDN .microsoft.com / EN-US /库/ system.runtime.caching.memorycache.aspx



您将需要添加System.RunTime。缓存组装为您的应用提供参考。 。下面是一个辅助类添加项目,并从缓存中删除

 使用系统; 
使用System.Runtime.Caching;

公共静态类CacheHelper
{
公共静态无效SaveTocache(字符串cacheKey,对象savedItem,日期absoluteExpiration)
{
MemoryCache.Default.Add( cacheKey,savedItem,absoluteExpiration);
}

公共静态牛逼GetFromCache< T>(串cacheKey)其中T:类
{
返回MemoryCache.Default [cacheKey]为T;
}

公共静态无效RemoveFromCache(字符串cacheKey)
{
MemoryCache.Default.Remove(cacheKey);
}

公共静态布尔IsIncache(字符串cacheKey)
{
返回MemoryCache.Default [cacheKey]!= NULL;
}
}



关于这样做的好处是,它是线程安全的,它需要为您自动到期缓存的照顾。所以基本上你所要做的就是检查是否正从的MemoryCache项目为空或不是。 注意但是,这种的MemoryCache仅在.NET 4.0 +



如果您的应用程序是一个Web应用程序,然后使用System.Web.Caching,而不是的MemoryCache。因为.NET 1.1 System.Web.Caching已经可用,还有你必须添加到您的项目没有额外的引用。 。继承人相同的助手类网页



 使用的System.Web; 

公共静态类CacheHelper
{
公共静态无效SaveTocache(字符串cacheKey,对象savedItem,日期absoluteExpiration)
{
如果(IsIncache(cacheKey) )
{
HttpContext.Current.Cache.Remove(cacheKey);
}

HttpContext.Current.Cache.Add(cacheKey,savedItem,空,System.Web.Caching.Cache.NoAbsoluteExpiration,新的TimeSpan(0,10,0)的System.Web .Caching.CacheItemPriority.Default,NULL);
}

公共静态牛逼GetFromCache< T>(串cacheKey)其中T:类
{
返回HttpContext.Current.Cache [cacheKey]为T;
}

公共静态无效RemoveFromCache(字符串cacheKey)
{
HttpContext.Current.Cache.Remove(cacheKey);
}

公共静态布尔IsIncache(字符串cacheKey)
{
返回HttpContext.Current.Cache [cacheKey]!= NULL;
}
}

有,你可以使用其他缓存过期策略这两种模式,例如缓存基于文件的路径(S),以便对一个文件时自动改变缓存过期,SQL缓存依赖项(不更改SQL服务器的定期轮询),滑动过期或者你可以建立自己的。他们进来非常方便。


Im new to generics in c#, and I'm trying to create a storage that other parts of my program can ask for models objects. The idea was that if my cache class has the object, it checks its date and returns it if the object is not older then 10 min. If it is older then 10 min it downloads a updated model from the server online. It it does not have the object is downloads it and returns it.

But I'm having some problems pairing my objects with a DateTime, makeing it all generic.

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

解决方案

Check out the memory cache class available as part of the .NET framework http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx

You'll need to add the System.RunTime.Caching assembly as a reference to your application. The following is a helper class to add items and remove them from cache.

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

The nice thing about this is that it's thread safe, and it takes care of expiring the cache automatically for you. So basically all you have to do is check if getting an item from MemoryCache is null or not. Note however that MemoryCache is only available in .NET 4.0+

If your application is a web application then use System.Web.Caching rather than MemoryCache. System.Web.Caching has been available since .NET 1.1 and there's no additional references you have to add to your project. Heres the same helper class for web.

using System.Web;

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

        HttpContext.Current.Cache.Add(cacheKey, savedItem, 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;
    }
}

There are other cache expiration policies that you can use for both of these patterns, for instance cache based on a file path(s) so that when a file changes the cache automatically expires, SQL cache dependency (does periodic polling of the SQL server for changes), sliding expiration or you could build your own. They come in really handy.

这篇关于我怎样才能创建缓存对象的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆