缓存通用管理类 + 缓存 HttpContext.Current.Cache 和 HttpRuntime.Cache 的区别

野性酷女 2024-02-18 19:53 160阅读 0赞

  以前写asp.net时用HttpContext.Current.Cache存缓存很好用,今天写了一个windows服务程序,HttpContext.Current.Cache存缓存的时候还好,取的时候一直报错“未将对象引用到实例”很郁闷,查询了一下资料才明白引用程序缓存要用HttpRuntime.Cache…

  我们先看MSDN上的解释:

   HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象。
  HttpRuntime.Cache:获取当前应用程序的Cache。

附带的写了一个操作缓存的通用类,在应用程序中使用,如果要在asp.net中有,只需把HttpRuntime.Cache改为HttpContext.Current.Cache即可,代码如下:

ContractedBlock.gif ExpandedBlockStart.gif 代码

  1. using
  2. System;
  3. ///
  4. <summary>
  5. ///
  6. author:Stone_W
  7. ///
  8. date:2010.12.1
  9. ///
  10. desc:缓存的管理类
  11. ///
  12. 注意:要添加对引用 System.Web
  13. ///
  14. </summary>
  15. public
  16. class
  17. MyCacheTools : System.Web.SessionState.IRequiresSessionState
  18. {
  19. #region
  20. 存入Cache
  21. ///
  22. <summary>
  23. ///
  24. 存入Cache
  25. ///
  26. </summary>
  27. ///
  28. <param name="key">
  29. 缓存key
  30. </param>
  31. ///
  32. <param name="value">
  33. 缓存的值
  34. </param>
  35. ///
  36. <param name="time_HH">
  37. xx小时
  38. </param>
  39. ///
  40. <returns>
  41. 是否执行成功[bool]
  42. </returns>
  43. public
  44. static
  45. bool
  46. SetCache(
  47. string
  48. key,
  49. object
  50. value,
  51. int
  52. time_HH)
  53. {
  54. bool
  55. result
  56. =
  57. false
  58. ;
  59. try
  60. {
  61. DateTime dt
  62. =
  63. DateTime.Now.AddHours(time_HH);
  64. System.Web.HttpRuntime.Cache.Insert(key, value,
  65. null
  66. ,
  67. dt, System.Web.Caching.Cache.NoSlidingExpiration);
  68. result
  69. =
  70. true
  71. ;
  72. }
  73. catch
  74. (Exception ex) { }
  75. return
  76. result;
  77. }
  78. #endregion
  79. #region
  80. 取得Cache
  81. ///
  82. <summary>
  83. ///
  84. 取得Cache
  85. ///
  86. </summary>
  87. ///
  88. <param name="key">
  89. key
  90. </param>
  91. ///
  92. <returns>
  93. object类型
  94. </returns>
  95. public
  96. static
  97. object
  98. GetCache(
  99. string
  100. key)
  101. {
  102. return
  103. System.Web.HttpRuntime.Cache.Get(key);
  104. }
  105. #endregion
  106. #region
  107. 查询Cache是否存在
  108. ///
  109. <summary>
  110. ///
  111. 查询Cache是否存在
  112. ///
  113. </summary>
  114. ///
  115. <param name="key">
  116. key
  117. </param>
  118. ///
  119. <returns>
  120. bool
  121. </returns>
  122. public
  123. static
  124. bool
  125. IsCacheExist(
  126. string
  127. key)
  128. {
  129. bool
  130. result
  131. =
  132. false
  133. ;
  134. object
  135. temp
  136. =
  137. System.Web.HttpRuntime.Cache.Get(key);
  138. if
  139. (
  140. null
  141. !=
  142. temp)
  143. {
  144. result
  145. =
  146. true
  147. ;
  148. }
  149. return
  150. result;
  151. }
  152. #endregion
  153. }

ps:HttpContext.Current.Cache 为null 这个问题搞的我很痛苦,最后还是解决了,希望此篇文章对大家有用!

发表评论

表情:
评论列表 (有 0 条评论,160人围观)

还没有评论,来说两句吧...

相关阅读

    相关 一级缓存二级缓存区别

    什么是缓存? 缓存是介于应用程序和物理数据源之间,是为了降低应用程序对物理数据源的访问频率,从而提高应用程序的运行性能。 缓存的介质一般是内存,所以读写速度很快,如果缓存中