Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
ASP.NET 3.5 Professionals If you are an experienced ASP.NET programmer, this is the forum for your 3.5 questions. Please also see the Visual Web Developer 2008 forum.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 3.5 Professionals section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
 
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old May 27th, 2010, 06:55 PM
Friend of Wrox
Points: 1,749, Level: 16
Points: 1,749, Level: 16 Points: 1,749, Level: 16 Points: 1,749, Level: 16
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2007
Location: San Diego, CA, USA.
Posts: 477
Thanks: 10
Thanked 19 Times in 18 Posts
Default 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).
__________________
-------------------------

Whatever you can do or dream you can, begin it. Boldness has genius, power and magic in it. Begin it now.
-Johann von Goethe

When Two Hearts Race... Both Win.
-Dove Chocolate Wrapper

Chroniclemaster1, Founder of www.EarthChronicle.com
A Growing History of our Planet, by our Planet, for our Planet.
  #2 (permalink)  
Old May 28th, 2010, 02:59 AM
Imar's Avatar
Wrox Author
Points: 72,035, Level: 100
Points: 72,035, Level: 100 Points: 72,035, Level: 100 Points: 72,035, Level: 100
Activity: 100%
Activity: 100% Activity: 100% Activity: 100%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,079
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

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
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
  #3 (permalink)  
Old May 29th, 2010, 03:04 AM
Friend of Wrox
Points: 1,749, Level: 16
Points: 1,749, Level: 16 Points: 1,749, Level: 16 Points: 1,749, Level: 16
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2007
Location: San Diego, CA, USA.
Posts: 477
Thanks: 10
Thanked 19 Times in 18 Posts
Default

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

Whatever you can do or dream you can, begin it. Boldness has genius, power and magic in it. Begin it now.
-Johann von Goethe

When Two Hearts Race... Both Win.
-Dove Chocolate Wrapper

Chroniclemaster1, Founder of www.EarthChronicle.com
A Growing History of our Planet, by our Planet, for our Planet.
  #4 (permalink)  
Old May 29th, 2010, 03:24 AM
Imar's Avatar
Wrox Author
Points: 72,035, Level: 100
Points: 72,035, Level: 100 Points: 72,035, Level: 100 Points: 72,035, Level: 100
Activity: 100%
Activity: 100% Activity: 100% Activity: 100%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,079
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

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
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
The Following User Says Thank You to Imar For This Useful Post:
chroniclemaster1 (May 30th, 2010)
  #5 (permalink)  
Old May 30th, 2010, 09:05 PM
Friend of Wrox
Points: 1,749, Level: 16
Points: 1,749, Level: 16 Points: 1,749, Level: 16 Points: 1,749, Level: 16
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2007
Location: San Diego, CA, USA.
Posts: 477
Thanks: 10
Thanked 19 Times in 18 Posts
Default

Quote:
Originally Posted by Imar View Post
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.
__________________
-------------------------

Whatever you can do or dream you can, begin it. Boldness has genius, power and magic in it. Begin it now.
-Johann von Goethe

When Two Hearts Race... Both Win.
-Dove Chocolate Wrapper

Chroniclemaster1, Founder of www.EarthChronicle.com
A Growing History of our Planet, by our Planet, for our Planet.
  #6 (permalink)  
Old May 31st, 2010, 04:00 AM
Imar's Avatar
Wrox Author
Points: 72,035, Level: 100
Points: 72,035, Level: 100 Points: 72,035, Level: 100 Points: 72,035, Level: 100
Activity: 100%
Activity: 100% Activity: 100% Activity: 100%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,079
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

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
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
caching neeraj BOOK: Professional ASP.NET 4 : in C# and VB 2 July 27th, 2010 01:33 AM
caching neeraj BOOK: Professional ASP.NET 4 : in C# and VB 0 April 14th, 2010 04:56 PM
caching jezywrap ASP.NET 2.0 Professional 0 February 27th, 2007 05:00 PM
caching? freaknfreak HTML Code Clinic 1 January 24th, 2006 12:10 PM
Caching bmains ASP.NET 1.x and 2.0 Application Design 4 February 27th, 2004 09:06 AM



All times are GMT -4. The time now is 03:51 PM.


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