开发者

Cache static class's Data in Silverlight

I have static class that holds some info

public static class SampleDataCache
{开发者_运维技巧
    private static Dictionary<string,SampleData> cacheDict = new Dictionary<string,object>()

    public static Get(string key)
    {
        if(!cacheDict.Contains[key])
            cacheDict.Add(key,new SampleData());

        return cacheDict[key];
    }
}

And when I refresh page I want SampleDataCache to keep its data.

Can I achieve this in simple way?


Since the cache, in its current form, is stored in memory then the data is naturally cast into oblivion when the page refreshes - that's a new instance of the application starting there. You might, however, be interested in utilising isolated storage in order to persist data per-user.

With isolated storage you essentially have a contained file system into which you can store data and then further retrieve it. One step in the right direction could be to make a class you want to represent a 'piece' of cached data, make it serializable, then using your static class as the cache controller you can read and write these objects from and to isolated storage.

Quickstart: Isolated Storage in Silverlight


You should remember about extra if (nobody understand that ;/). And also you can be more generic and type safely. You can Look below, this is example of well written caching pattern also can be used as an aspect.

using System;
using System.Collections.Generic;

namespace SampleDataCache {

  public class SampleData {
    public string Name { get; set; }
  }

  public static class DataCache {
    private static readonly Dictionary<string, object> CacheDict
      = new Dictionary<string, object>();

    private static readonly object Locker = new object();

    public static T Get<T>(string key, Func<T> getSampleData) {
      if (!CacheDict.ContainsKey(key)) {
        lock (Locker)
          if (!CacheDict.ContainsKey(key)) {
            CacheDict.Add(key, getSampleData());
          }
      }
      return (T)CacheDict[key];
    }
  }

  public class Program {
    private static SampleData CreateSampleData() {
      return new SampleData() { Name = "Piotr Sowa" };
    }

    private static void Main(string[] args)
    {
      SampleData data = DataCache.Get("Author", CreateSampleData);
    }
  }
}

Regards

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜