Thursday 1 July, 2010

Using the application Web Cache

It is a good idea to use caching for frequently accessed objects to reduce trips to the database or your web services. Here is an example of using the System.Web application cache. You can even use this in dll's outside of your web project, as long as you reference System.Web.

  1. string cacheName = "objectNameCache";
  2. int cacheDurationMinutes = 10;
  3. var cache = System.Web.HttpRuntime.Cache;
  4. cache.Insert(cacheName, quote, null, DateTime.UtcNow.AddMinutes(cacheDurationMinutes), TimeSpan.Zero);
  5. // now to access it... First check if null, then simply cast cache to outcoming object.
  6. if (cache[cacheName] != null)
  7. {
  8. quote = (DataTransferObjects.QuoteData)cache[cacheName];

No comments:

Post a Comment