2013-08-12 20 views
10

C# 'de jenerikler için yeni ve programımın diğer bölümlerinin model nesneleri isteyebileceği bir depolama alanı oluşturmaya çalışıyorum. Buradaki öneri, eğer önbellek sınıfım nesneye sahipse, tarihini kontrol eder ve eğer nesne 10 dakikadan büyük değilse geri döndürürdü. 10 yaşından büyükse, çevrimiçi olarak sunucudan güncelleştirilmiş bir model indirir. Nesnenin yüklemediği ve döndürmediği bir şey yoktur.Nesneleri önbelleğe alan bir sınıfı nasıl oluşturabilirim?

Ancak, nesnelerimi bir DateTime ile eşleştirerek bazı sorunları çözüyorum.

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

Eşleşen nesnelerde sorun/hata hakkında daha fazla bilgi verebilir misiniz? Muhtemelen 'DatedObject' için yapı yerine sınıfı deneyebilir ve kendi sınıf nesnesini oluşturmak istemezseniz, Tuple – Rex

+0

[Akavache] (https://github.com/github/Akavache) 'yi denemeye değer olabilirsiniz. içine. –

cevap

22

Kontrol dışarı .NET framework Başvurunuzda bir referans olarak System.RunTime.Caching takımını eklemeniz gerekir http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx

parçası olarak kullanılabilir önbellek sınıfı. Aşağıdakiler, öğe eklemek ve bunları önbellekten kaldırmak için yardımcı bir sınıftır.

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

bu konuda güzel bir şey parçacığının güvenli olmasıdır, ve sizin için otomatik olarak önbelleğe süresi dolan ilgilenir. Yani temelde tüm yapmanız gereken MemoryCache'den bir öğe almanın boş olup olmadığını kontrol etmektir. Not Ancak, MemoryCache yalnızca .NET 4.0+

içinde kullanılabilir. Uygulamanız bir web uygulamasıysa, MemoryCache yerine System.Web.Caching kullanın. System.Web.Caching .NET 1.1'den beri kullanılabilir ve projenize eklemek istediğiniz ek referans bulunmamaktadır. Heres web için aynı yardımcı sınıftır.

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

bir dosya yolu (ler) dayalı örnek önbelleği için bu desenlerin her ikisi için kullanabileceğiniz diğer önbellek son kullanma politikaları vardır ki, bir dosya (otomatik önbelleği değiştirir SQL önbellek bağımlılığı sona erdiğinde yapar Değişim için SQL sunucusunun periyodik yoklaması), süreyi doldurarak veya kendi başınıza inşa edebilirsiniz. Gerçekten işe yarıyorlar.

İlgili konular