p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   ASP.NET 3.5 Professionals (http://p2p.wrox.com/forumdisplay.php?f=352)
-   -   Caching (http://p2p.wrox.com/showthread.php?t=79568)

chroniclemaster1 May 27th, 2010 06:55 PM

Caching
 
Based on the page life cycle, all the application code which runs from the App_Code folder is destroyed at the end of a request correct?

Yet I've seen people use caching that only seemed to make sense if it was going to persist from one page request to another (including different Wrox books, among other places). How is this accomplished?

I sold on the desirability of storing important information in the application so you don't have to keep looking it up in a web service or DB, but I don't understand how a custom cache object survives the end of the page request without storing it in an external resource (which kinda defeats the purpose).

Imar May 28th, 2010 02:59 AM

Quote:

all the application code which runs from the App_Code folder is destroyed at the end of a request correct?

Waht makes you think that?

Objects created in your code and stored in the Cache will remain there until a) they expire due to one of their constraints, b) the cache decides to ditch them or c) the application restarts.

Let's say you have a class Person in App_Code:

Code:


public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

Then create one in Default.aspx.cs:

Code:


Person imar = new Person() { FirstName = "Imar", LastName = "Spaanjaars" };

and then store it in the Cache:

Code:


Cache["MyCacheKey"] = imar;

You can retrieve the item later; possible in a different page, during a different user's request, from a different session or even days later, provided the cache maintained the item.

The objects are stored within the Application Domain and as such are globally available from the perspective of the application.

Hope this helps,

Imar

chroniclemaster1 May 29th, 2010 03:04 AM

Cool. So as long as the application isn't recycled, you can fetch "whatever" from the Cache object days later?

One other related question. I found one of the code samples I was remembering. Does it become part of the application state as well, and can it be fetched days later (again provided the application isn't recycled in between)?

If so, I'm wondering if the magic happens because the Dictionary is a static field?

Code:

class MyCache<K, V> {
  private static Dictionary<K, V> _objectCache;

  public MyCache() {
      MyCache<K, V>._objectCache = new Dictionary<K, V>();
  }

  private V findValueInDB(K key) {
      // code to retrieve value from external resource
  }

  public V lookupValue(K key) {
      V retVal;
      if (_objectCache.ContainsKey(key) == true) {
        __objectCache.TryGetValue(key, out retVal);
      } else {
        retVal = findValueInDB(key);
      }
      return retVal;
  }
}


Imar May 29th, 2010 03:24 AM

Quote:

Cool. So as long as the application isn't recycled, you can fetch "whatever" from the Cache object days later?
No, that's not true. It might be there, it might not.
Quote:

Objects created in your code and stored in the Cache will remain there until a) they expire due to one of their constraints, b) the cache decides to ditch them or c) the application restarts.
Stuff you store in the cache isn't necessarily there forever. You can put restrictions on its lifetime or ASP.NET may decide to delete it. You should always check if it's there. E.g.:

Code:


SomeClass myInstance = Cache["SomeKey"] as SomeClass;
if (myInstance == null)
{
  myInstance = WhatEverItTakesToCreateMyInstance();
  Cache.Insert("SomeKey", myInstance);
}

Note that the Cache has Add and Insert methods with various overloads to determine lifetime, dependencies and expiration policies.

Quote:

Does it become part of the application state as well, and can it be fetched days later (again provided the application isn't recycled in between)?
Yes, in this case it stays there until the application is restarted. Indeed, static fields are tied to the application domain so anything you store in a static field is available during the lifetime of the app domain.

The nice thing about the cache is that it can do memory management for you. E.g. stuff that consumes a lot of money and / or that is infrequently used can be thrown out of the cache, something you cannot accomplish with static fields.

Cheers,

Imar

chroniclemaster1 May 30th, 2010 09:05 PM

Quote:

Originally Posted by Imar (Post 258489)
No, that's not true. It might be there, it might not.
Stuff you store in the cache isn't necessarily there forever. You can put restrictions on its lifetime or ASP.NET may decide to delete it. You should always check if it's there.

Yes, in this case it stays there until the application is restarted. Indeed, static fields are tied to the application domain so anything you store in a static field is available during the lifetime of the app domain.

The nice thing about the cache is that it can do memory management for you. E.g. stuff that consumes a lot of money and / or that is infrequently used can be thrown out of the cache, something you cannot accomplish with static fields.

Thank you for the sample cache code. :)

And for the first time I really see a value in static classes. So the static fields store information for the entire app, and the static functions are a good option if you have some kind of frequently used cross application functions that you need to run. It now makes sense why I've seen guys choose to build links from a static function. It's one piece of code that all pages are going to be running multiple times.

So static fields and the Cache[] object are simply two different caching strategies. Moreover it looks like the Cache[] is a better choice for caching things you only want for a limited amount of time (because a static field won't recycle them), and for things you don't need all the time. On the other hand, a static field may be a better choice if you need to access the information a lot over a long period of time. Further, minimizing the amount of information stored in the cache is important, but it's much more critical for a static field because it's going to be around until the application recycles. That's an advantage of the Cache[], because it will recycle things for you, if it determines the space is better used for something else.

Imar May 31st, 2010 04:00 AM

Yes, that pretty much summarizes it. A few remarks though:

I don't see static fields or properties as a cache, although they could fulfill that purpose. I mainly use them for simple fields such as configuration. For example:

Code:


public class AppConfiguration
{
  public static string FromAddress
  {
    get
    {
      string result = WebConfigurationManager.AppSettings.Get("FromAddress");
      if (!string.IsNullOrEmpty(result))
      {
        return result;
      }
      throw new Exception("AppSetting FromAddress not found in web.config file.");
    }
  }
}

This static property can now be called as:

myMessage.From = new MailAddress(AppConfiguration.FromAddress);

Note that inside the getter you could "cache" the return value of WebConfigurationManager.AppSettings.Get in yet another static, and private field to avoid the overhead of accessing the configuration more than once. However, AFAIK, the WebConfigurationManager already minimizes the overhead.

So, the static field serves as a wrapper around the real data, in this example data stored in the web.config file.

The Cache, on the other hand, doesn't act as a wrapper, but serves as an alternative. The real data is copied (for example, the result of a DB query) and stored in the cache for quicker access. The benefits are quick access, at the cost of memory consumption and the risk of stale data.

Hope this helps,

Imar


All times are GMT -4. The time now is 05:21 PM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.