请选择 进入手机版 | 继续访问电脑版
查看: 174|回复: 0

[.NET开发] .NET 缓存处理类

3万

主题

3万

帖子

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
100197
发表于 2015-11-23 17:52:05
.NET 缓存处理类。
用法:Just copy this code into a new class file (.cs) and add it to your ASP .NET website. One thing to keep in mind is that data stored in ASP .NET Cache can be accessible across all sessions. So when creating a cacheID for the object to be stored, it must be unique (or it could be overwritten). I usually store the unique cacheID in the session and then use that to referrence the cacheID. (e.g. CacheHandler.Write(Session["MyCacheData"], myData);)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web.Caching;
  4. using System.Web;
  5. /// <summary>
  6. /// This class reads/writes to ASP .NET server cache. For the sake of
  7. /// simplicity, the class writes objects to cache with no expirateion.
  8. /// Use the Remove() function to programmatically remove objects stored
  9. /// from the server cache. This class was created as an alternative to
  10. /// storing large objects in the session.
  11. /// </summary>
  12. public class CacheHandler
  13. {
  14. public static bool Write(string cacheID, object data)
  15. {
  16. if (HttpContext.Current == null)
  17. return false;
  18. if (cacheID == null || cacheID.Equals(""))
  19. return false;
  20. HttpRuntime.Cache.Insert(
  21. cacheID, data, null, Cache.NoAbsoluteExpiration,
  22. Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null
  23. );
  24. return true;
  25. }
  26. public static object Read(string cacheID)
  27. {
  28. if (HttpContext.Current == null)
  29. return null;
  30. return HttpRuntime.Cache.Get(cacheID);
  31. }
  32. public static void Remove(string cacheID)
  33. {
  34. if (HttpContext.Current == null )
  35. return;
  36. if (cacheID == null || cacheID.Equals(""))
  37. return;
  38. HttpRuntime.Cache.Remove(cacheID);
  39. }
  40. }
复制代码


回复

使用道具 举报