1、引用 System.Runtime.Caching
2、源 msdn
1 //實例化MemoryCache類 2 ObjectCache cache = MemoryCache.Default; 3 //讀取緩存 4 string fileContents = cache["filecontents"] as string; 5 if (fileContents == null) 6 { 7 StringBuilder strb = new StringBuilder(); 8 path = AppDomain.CurrentDomain.BaseDirectory + "Resources/caching.txt"; 9 //讀取文件內容 10 StreamReader sr = new StreamReader(path, Encoding.Default); 11 String line; 12 while ((line = sr.ReadLine()) != null) 13 { 14 strb.Append(line.ToString()); 15 } 16 fileContents = strb.ToString() + "---" + DateTime.Now; 17 //設置緩存過期時間 18 CacheItemPolicy policy = new CacheItemPolicy(); 19 policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0); 20 21 List<string> filePaths = new List<string>(); 22 filePaths.Add(path); 23 //添加緩存 24 cache.Set("filecontents", fileContents, policy); 25 }