如何使用 Outputcache 保存列表所有用户都可以看到?

发布于 2024-11-29 13:27:17 字数 165 浏览 3 评论 0原文

大家好,我有一个列表,我想向所有用户显示相同的列表,而不需要在我的数据库中进行其他查询。 在论坛上搜索我发现 OutPutCache 是我可以遵循的最佳方法,但我真的不明白我该怎么做。

[编辑]

OutPutCache 是做到这一点的最佳方法吗?

Hello guys I have a List that I want to show for all users the same list without make an other query at my database.
Searching on forums I found that OutPutCache is the best way that I can follow, but I really don't understand how can I do that.

[EDIT]

Is OutPutCache the best way to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赠佳期 2024-12-06 13:27:17

你已经走得太远了;如果您只想将一个 List 保留在内存中一段时间​​,则不需要输出缓存。输出缓存是指当您想要缓存整个呈现的页面以发送给用户而不调用控制器时。

您只需要通过共享变量或普通的旧缓存将对象保留在内存中。

public class MyListFetcher<T>
{
     public List<T> FetchData()
     {
          List<T> obj = HttpRuntime.Cache["myObjectCacheKey"] as List<T>;

          if(obj != null)
             return obj;

          obj = FetchDataFromDatabase();

          HttpRuntime.Cache.Insert("myObjectCacheKey", obj, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

          // Inserts the item and keeps it there for five minutes; then the cache will be invalidated. No sliding expiration

         return obj;
     } 

     protected List<T> FetchDataFromDatabase()
     {
         // Your DB fetch code
     }
}

You're getting too far along here; if all you have is a single List<T> that you want to keep in memory for a while, you dont need output caching. Output caching is when you want to cache the entire rendered page to send to users without recalling your controller.

You just need to persist the object in memory, either via a shared variable or plain old caching.

public class MyListFetcher<T>
{
     public List<T> FetchData()
     {
          List<T> obj = HttpRuntime.Cache["myObjectCacheKey"] as List<T>;

          if(obj != null)
             return obj;

          obj = FetchDataFromDatabase();

          HttpRuntime.Cache.Insert("myObjectCacheKey", obj, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

          // Inserts the item and keeps it there for five minutes; then the cache will be invalidated. No sliding expiration

         return obj;
     } 

     protected List<T> FetchDataFromDatabase()
     {
         // Your DB fetch code
     }
}
萌逼全场 2024-12-06 13:27:17

控制器方法上的 [OutputCache] 属性将缓存查询结果 - 如果使用 VaryByParam 参数,这将缓存该参数的结果,从而减少从控制器方法调用数据库的次数。

The [OutputCache] attribute on a controller method will cache the result of a query - if you use the VaryByParam parameter, this will cache the result for that parameter, reducing the number of calls to the database from the controller method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文