2014-01-30 7 views
1

Я намереваюсь использовать мощные библиотеки кеширования, которые представлены в .Net 4.0 в приложении Windows Forms. До сих пор MemoryCache делает все, что мне нужно, за исключением сохранения его содержимого в файл. То, что я пытаюсь сделать, - это сохранить кеш в файле при выходе приложения, а затем, когда приложение будет открыто снова, я должен буду писать из файла и помещать его содержимое в MemoryCache. Я знаю, что я могу просто сериализовать экземпляр в двоичном виде на диске, но опять же, я не знаю, как его преобразовать обратно в *MemoryCache*.Сохранение содержимого MemoryCache в файл

Ваша помощь нам очень ценится.

ответ

0

Я закончил реализацию своего собственного проекта Cache. Надеюсь, это кому-то поможет:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.Text; 

namespace CachingDemo 
{ 
    class CachedMemory 
    { 
     System.Collections.Specialized.OrderedDictionary cache = null; 
     private String persistenceFilePath = null; 
     private int cacheSizeLimit; 
     public static readonly int CACHE_SIZE_NO_LIMIT = -1; 

     public CachedMemory(int initialCapacity, int cacheSizeLimit, string persistenceFilePath) 
     { 

      this.cache = new System.Collections.Specialized.OrderedDictionary(initialCapacity); 
      this.persistenceFilePath = persistenceFilePath; 
      this.cacheSizeLimit = cacheSizeLimit; 

     } 

     public int getCacheSize() 
     { 
      return this.cache.Count; 
     } 

     public CachedMemory(int cacheSizeLimit, string cacheFilePath) 
     { 
      initializeCache(cacheFilePath, cacheSizeLimit); 
     } 

     private void initializeCache(string cacheFilePath, int cacheSizeLimit) 
     { 
      this.cacheSizeLimit = cacheSizeLimit; 
      using (FileStream fileStream = new FileStream(cacheFilePath, FileMode.Open)) 
      { 
       IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
       this.cache = (System.Collections.Specialized.OrderedDictionary)bf.Deserialize(fileStream); 
       fileStream.Close(); 
      } 

      //In case the deserialized OrderedDictionary had more contents than the limit, we need to shrink it to make its size equal to the limit 
      if (this.cacheSizeLimit != CACHE_SIZE_NO_LIMIT && this.cache.Keys.Count > this.cacheSizeLimit) 
      { 
       int difference = this.cache.Keys.Count - this.cacheSizeLimit; 

       for (int i = 0; i < difference; i++) 
       { 
        cache.RemoveAt(0); 
       } 
      } 
     } 

     public string get(string key) 
     { 
      return cache[key] as string; 
     } 

     public string get(int index) 
     { 
      return cache[index] as string; 
     } 


     public void add(string key, string value) 
     { 
      //An ordered dictionary would throw an exception if we try to insert the same key again, so we have to make sure that the newly 
      //introduced key is not a duplicate. 
      if (this.cache.Contains(key)) 
      { 
       this.cache.Remove(key); 

      } 
      else 
       if (this.cacheSizeLimit != CACHE_SIZE_NO_LIMIT && this.cache.Count == this.cacheSizeLimit) 
       { 
        this.cache.RemoveAt(0); 

       } 

      this.cache.Add(key, value); 
     } 

     public void persist() 
     { 
      using (FileStream fileStream = new FileStream(persistenceFilePath, FileMode.Create)) 
      { 
       IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
       bf.Serialize(fileStream, this.cache); 
       fileStream.Close(); 
      } 
     } 
    } 
} 
+0

так что вы просто хотите использовать строки кеша? вы где-то скрываете механизм сериализации? –

+0

Приведенный выше пример может работать для объектов, созданных с использованием пользовательских классов, учитывая, что они определены как сериализуемые. –

Смежные вопросы