开发者

How can I use Outputcache to save a list<T> that all users can see?

开发者 https://www.devze.com 2023-03-28 05:53 出处:网络
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.

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 fol开发者_如何学编程low, but I really don't understand how can I do that.

[EDIT]

Is OutPutCache the best way to do that?


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
     }
}


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.

0

精彩评论

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