<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Alan Northam : C#</title><link>http://devlicio.us/blogs/alan_northam/archive/tags/C_2300_/default.aspx</link><description>Tags: C#</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Cold, Hard, Cache!</title><link>http://devlicio.us/blogs/alan_northam/archive/2008/03/06/cold-hard-cache.aspx</link><pubDate>Fri, 07 Mar 2008 04:04:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:39576</guid><dc:creator>anortham</dc:creator><slash:comments>9</slash:comments><description>&lt;p&gt;Don&amp;#39;t get me wrong, I really like the Asp.Net Cache (or HttpRuntime.Cache or Uncle Daddy if you want to call it that... you&amp;#39;re a little odd aren&amp;#39;t you?), but sometimes it just can&amp;#39;t be trusted.&amp;nbsp; I mean, I just gave you (the cache) my precious object a second ago and now you claim you don&amp;#39;t have it?&amp;nbsp; Did you lose it?&amp;nbsp; Did you sell it on eBay?&amp;nbsp; Did you pawn it to support your habit?&amp;nbsp; Please at least tell me you got a decent price for it.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;One of the great things about the cache is also what makes it so untrustworthy. &amp;nbsp; Objects stored there are referenced with &lt;a href="http://msdn2.microsoft.com/en-us/library/system.weakreference.aspx" target="_blank"&gt;WeakReference&lt;/a&gt; so if your sever starts getting low on memory GC will collect objects from the cache to free some up.&amp;nbsp; Also take into account that if you put an object in Cache and set it to expire after X minutes, when you go back to retreive it, do you really know how long it&amp;#39;s been?&lt;/p&gt;
&lt;p&gt;So what we want is a way to tell the cache &amp;quot;I want this specific object (a yellow Tonka dumptruck, metal, not plastic) and if you don&amp;#39;t have it, here are instructions on how to get it&amp;quot;.&lt;/p&gt;
&lt;p&gt;Something like this:&lt;/p&gt;
&lt;p&gt;

using System;
using System.Reflection;
using System.Web;
using System.Web.Caching;
using log4net;
public delegate bool Factory&amp;lt;T&amp;gt;( out T instance );
public class CacheHelper
{
    private static readonly ILog log =
        LogManager.GetLogger(
            MethodBase.GetCurrentMethod().DeclaringType );

    private static readonly Cache cache = HttpRuntime.Cache;
    private CacheHelper(){}

    public static T GetFromCache&amp;lt;T&amp;gt;(string key, int cacheTimeInMinutes, Factory&amp;lt;T&amp;gt; retrieveMethod) where T:class
    {
        T target = cache[key] as T;
        if(target == null)
        {
            log.Info( &amp;quot;Cache miss for key:&amp;quot; + key + &amp;quot;  type:&amp;quot; + typeof(T));
            if(retrieveMethod(out target))
            {
                cache.Insert( key, target, null, DateTime.Now.AddMinutes( cacheTimeInMinutes ),
                    Cache.NoSlidingExpiration, CacheItemPriority.Normal, OnRemove );
            }            
        }
        else
        {
            log.Info( &amp;quot;Cache hit for key:&amp;quot; + key + &amp;quot;  type:&amp;quot; + typeof(T));
        }
        return target;
    }

    public static void OnRemove( string key, object cacheItem, CacheItemRemovedReason reason )
    {
        log.Info( &amp;quot;Object removed from cache: Key-&amp;quot; + key + &amp;quot;: Reason-&amp;quot; + reason);
    }

    public static void RemoveFromCache(string key)
    {
        cache.Remove( key );
    }
}&lt;/p&gt;
&lt;p&gt;
Usage would look like this:
&lt;/p&gt;
&lt;p&gt;
List&amp;lt;string&amp;gt; searchList = CacheHelper.GetFromCache&amp;lt;List&amp;lt;string&amp;gt;&amp;gt;(
            key,
            5,
            delegate( out List&amp;lt;string&amp;gt; instance ) { return SomeClass.GetSearchList( key, out instance ); } );
&lt;/p&gt;
&lt;p&gt;
I call it the code equivalent of &amp;quot;Trust but verify&amp;quot;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=39576" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/ASP.NET/default.aspx">ASP.NET</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/Cache/default.aspx">Cache</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/HttpRuntime.Cache/default.aspx">HttpRuntime.Cache</category></item><item><title>Casting options in C#</title><link>http://devlicio.us/blogs/alan_northam/archive/2007/10/07/casting-options-in-c.aspx</link><pubDate>Sun, 07 Oct 2007 19:27:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:38628</guid><dc:creator>anortham</dc:creator><slash:comments>9</slash:comments><description>&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; What is the best way to cast from one type to another in C#?&amp;nbsp; This question came up at work last week while I was looking through some older code.&amp;nbsp; The code in question was using the C style casting syntax.&amp;nbsp; I have started to use the &amp;quot;as&amp;quot; style cast more often and rewrote it.&amp;nbsp; Then I decided to do some research into the differences between the two styles to find out if one really is better than the other.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; The most obvious difference is that a C style case will throw and exception if the cast fails and the &amp;quot;as&amp;quot; style cast will simply return null.&amp;nbsp; So first you need to take into consideration what these differences will have on your code.&amp;nbsp; Will you need to wrap every cast in try/catch blocks?&amp;nbsp; Not if you use the &amp;quot;as&amp;quot; style, but you will need to check for null.&amp;nbsp; What about performance?&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; I read a dozen or so blog posts on the subject and they seemed to be pretty evenly divided with half insisting that one style was obviously superior and the other half convinced their chosen style was better.&amp;nbsp; That didn&amp;#39;t really help so I decided to do some testing on my own.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; I&amp;#39;ve attached a small test project for reference, it will allow you to select the number of casts to perform and the style and return the total time and average for each cast.&amp;nbsp; First let&amp;#39;s see what the difference looks like in IL (o is of type object in these examples).&lt;/p&gt;
&lt;p&gt;

((Person) o).Name
becomes:
IL_0036:  castclass  CastTest.Person
Person p = o as Person;
becomes:
IL_0036:  isinst     CastTest.Person
&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;So there is a difference at the IL level but is one a better performer?&amp;nbsp; I wrote three different test projects, the last of which you will find attached to this post.&amp;nbsp; Why did I write three?&amp;nbsp; Because with each test I was convinced that my results must be skewed because I was not seeing the&amp;nbsp; performance difference I expected.&amp;nbsp; I ran test casting 100,000, 1,000,000, 10,000,000 and 100,000,000 objects many times in difference orders, restarting the application between tests, not restarting between tests, clicking the button with my left hand, clicking with my right hand, every combination I could think of.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; What did I discover?&amp;nbsp; It was pretty anticlimactic.&amp;nbsp; In my opinion the difference was completely negligible.&amp;nbsp; That is, negligible if you aren&amp;#39;t throwing exceptions when casting with the C style cast.&amp;nbsp; The most stable set of test results I could get were casting 1,000,000 objects.&amp;nbsp; In this case, either style averaged 10.1 seconds total and averaged 0.0101 milliseconds.&amp;nbsp; We&amp;#39;re talking about a difference of 0.00005 milliseconds per cast.&amp;nbsp; I can&amp;#39;t really get worked up over that.&amp;nbsp; Of course, if you throw exceptions for each C style cast in that test, it&amp;#39;s over 10 times slower.&amp;nbsp; That&amp;#39;s something to consider!&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;  So will I pick one over the other?&amp;nbsp; The answer is an emphatic &amp;quot;meh&amp;quot;.&amp;nbsp; In code I will probably use the &amp;quot;as&amp;quot; style.&amp;nbsp; When doing things in markup related to databinding it&amp;#39;s extremely useful to be able to use the C style cast and I will continue to do so.&lt;br /&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=38628" width="1" height="1"&gt;</description><enclosure url="http://devlicio.us" length="75060" type="application/zip" /><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/IL/default.aspx">IL</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://devlicio.us/blogs/alan_northam/archive/tags/Casting/default.aspx">Casting</category></item></channel></rss>