2013-08-12 6 views
10

Im는 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; 
    } 
} 
+0

개체를 페어링 할 때의 문제/오류에 대한 자세한 내용을 제공 할 수 있습니까? 아마도 'DatedObject'의 구조 대신 클래스를 시도해 볼 수 있습니다. 자신 만의 클래스 객체를 만들지 않으려면 Tuple – Rex

+0

[Akavache] (https://github.com/github/Akavache)를 살펴볼 가치가 있습니다. 으로. –

답변

22

체크 아웃 .NET 프레임 워크 당신은 당신의 응용 프로그램에 대한 참조로 System.RunTime.Caching 어셈블리를 추가해야합니다 http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx

의 일부로 사용할 수있는 메모리 캐시 클래스를. 다음은 항목을 추가하고 캐시에서 항목을 제거하는 도우미 클래스입니다.

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 이상에서만 사용할 수 있습니다.

응용 프로그램이 웹 응용 프로그램 인 경우 MemoryCache 대신 System.Web.Caching을 사용하십시오. .NET 1.1부터 System.Web.Caching을 사용할 수 있었으며 프로젝트에 추가해야 할 참조가 없습니다. 웹용 헬퍼 클래스도 있습니다.

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

파일 경로 (들)을 기반으로 인스턴스 캐시는 이러한 패턴을 모두 사용할 수있는 다른 캐시 만료 정책이있다 있도록 파일 (자동으로 캐시를 변경, SQL 캐시 종속성이 만료되면 수행 변경 사항에 대한 SQL Server의 주기적 폴링), 만료 미끄러지거나 자신 만의 빌드를 만들 수 있습니다. 그들은 정말로 편리하게 들어온다.

관련 문제