ASP.Net Quick Tips - Caching (scottwater.com)
submitted by swatermasysk(255) 5 years, 2 months ago
A list of quick tips on asp.net caching.
3 comments |category: ASP.NET |Views: 12 Tweet
tags: ScottWatermasysk Caching Tips ASP.NET another
Add a live kick counter to your blog >>
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:
Simply copy and paste this HTML into your blog post.
posted by yesthatmcgurk(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
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...
posted by gavinjoyce(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
All tags Your tags
Suggest a new category
dpeterson(1273)
Telerik(409)
fdub(381)
amit.jain(273)
BlackWasp(259)
RobertTheGrey(259)
jalpesh(252)
bsenoff(240)
KodefuGuru(227)
KMillerr(226)