ASP.Net Quick Tips - Caching (scottwater.com)

submitted by swatermasyskswatermasysk(255) 5 years, 2 months ago

A list of quick tips on asp.net caching.

3 comments |category: |Views: 12

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by yesthatmcgurkyesthatmcgurk(4063) 5 years, 2 months ago 0

I like to use a generic method to try and get objects out of the cache:

internal static bool TryGetCacheItem<T>(string key, ref T value)
{
// HttpContext.Current may be nulled out during execution when the worker process shuts down
HttpContext context = HttpContext.Current;
if (context == null) return false;
Cache c = context.Cache;
if (c == null) return false;
try
{
object o = c[key];
if (o == null)
return false;

value = (T)o;
return true;
}
catch (InvalidCastException)
{
return false;
}
}

My TrySet method doesn't use generics; it does perform null checking and adds some default behaviors:
internal static bool TrySetCacheItem(
string key,
object value,
CacheDependency dependency,
DateTime expiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback)
{
// sanity checks
if (string.IsNullOrEmpty(key)) return false;
if (value == null) return false;
// defaults; change as per your policy
if (expiration == null)
expiration = Cache.NoAbsoluteExpiration;
if (slidingExpiration == null)
slidingExpiration = Cache.NoSlidingExpiration;
// checks to avoid null reference exceptions
HttpContext context = HttpContext.Current;
if (context == null) return false;
Cache c = context.Cache;
if (c == null)
return false;

c.Add(key, value, dependency, expiration, slidingExpiration, priority, onRemoveCallback);
return true;
}

Reply

posted by yesthatmcgurkyesthatmcgurk(4063) 5 years, 2 months ago 0

Come to think of it, I suppose I could do this:
if(o is T)
{
value = (T)o;
return true;
}
else
return false;

and avoid the catch block altogether...

Reply

posted by gavinjoycegavinjoyce(25.7k) 5 years, 2 months ago 0

To avoid over-caching on DotNetKicks I use a 'reluctant cache' pattern:

http://weblogs.asp.net/gavinjoyce/pages/The-Reluctant-Cache-Pattern.aspx

Reply

information Login or create an account to comment on this story