concept cache in category .net

appears as: cache, caches, cache, The caches, The cache
C# in Depth

This is an excerpt from Manning's book C# in Depth.

Here LogEntity is a partial method, and LoadAndCache loads an entity from the database and inserts it into the cache. You might want to use this instead:

The caches themselves are executable, which takes a while to understand. The C# compiler generates code to simply execute the call site’s L0 cache (which is a delegate accessed through the Target property). That’s it! The L0 cache has a single rule, which it checks when it’s called. If the rule matches, it executes the associated behavior. If the rule doesn’t match (or if this is the first call, so it doesn’t have even one rule), it calls into the L1 cache, which in turn calls into the L2 cache. If the L2 cache can’t find any matching rules, it asks the receiver or the binder to resolve the call. The results are then put into the cache for next time.

AOP in .NET

This is an excerpt from Manning's book AOP in .NET.

Many caching tools are available for many different types of programs (Microsoft’s Caching Application Block, NCache from Alachisoft, Windows Azure AppFabric for cloud caching). But I want to focus on how AOP can help with caching, not the caching technology itself. Therefore, I’m going to use a cache that’s most readily available to .NET developers: the ASP.NET Cache.

The cache is like a dictionary object that’s available to you to use in ASP.NET code. In ASP.NET Web Forms, Cache is inherited from the Page base class. In ASP.NET MVC, it’s available through HttpContext, which is inherited from the Controller base class. Failing all else, you can get it via HttpContext.Current.Cache.

4.3.4. Retrieving from the cache

Stored values in a cache aren’t useful unless we retrieve the values when they’re available. If GetValue is called with arguments for which we’ve already cached a value, then we can save a trip to the (slow) web service and retrieve the value out of cache instead of running the code inside of GetValue. If it turns out that the value hasn’t been cached, only then do we need to run the (slow) GetValue method. To do this, let’s add to CacheAspect by overriding the OnEntry method, as shown in the listing 4.25.

If there’s a value in the cache, then we need to set the return value of the bounded method and return immediately (without running the bounded method). Therefore, if there’s a cheesesteak at the border, there’s no reason to continue on to Philadelphia: the hard work has already been done.

Listing 4.26. Checking the cache in OnEntry

There are two pieces of PostSharp API that warrant further explanation. The first is args.ReturnValue. This property gets and sets the return value of the method being bounded (CarValueService’s GetValue method). We want GetValue to return the value that’s in the cache, and setting args.ReturnValue will accomplish that.