Posted By: Cyonix | Sep 15th, 2008 @ 3:36 AM
page 1 of 1
Comments: 0 | Views: 1215
Cyonix
Cyonix
Me
I modified this "CacheManager" from here: http://weblogs.asp.net/zowens/archive/2007/10/20/easier-way-to-manage-your-asp-net-cache.aspx

I figured someone else might find my version useful.
 <BR>public class CacheManager<BR>{<BR>    public TimeSpan CacheDuration { get; set; }<BR>    public List<string> Keys { get; set; }<BR>    private static object syncObject = new object();
<P>    public CacheManager(TimeSpan Duration)<BR>    {<BR>        Keys = new List<string>();<BR>        this.CacheDuration = Duration;<BR>    }</P>
<P>    public T GetAndCheck<T>(string Key, Func<T> GetItem)<BR>    {<BR>        if (HasKey(Key))<BR>        {<BR>            return Grab<T>(Key);<BR>        }<BR>        else<BR>        {<BR>            lock (syncObject)<BR>            {<BR>                if (HasKey(Key))<BR>                {<BR>                    return Grab<T>(Key);<BR>                }<BR>                else<BR>                {<BR>                    T item = GetItem();<BR>                    Insert<T>(Key, item, CacheItemPriority.Default);<BR>                    return item;<BR>                }<BR>            }<BR>        }<BR>    }</P>
<P>    private T Grab<T>(string Key)<BR>    {<BR>        return (T)HttpContext.Current.Cache[Key];<BR>    }</P>
<P>    private bool HasKey(string Key)<BR>    {            <BR>        return HttpContext.Current.Cache[Key] != null && Keys.Contains(Key);<BR>    }</P>
<P>    private void Insert<T>(string Key, T obj, CacheItemPriority priority)<BR>    {<BR>        if (!Keys.Contains(Key))<BR>            Keys.Add(Key);</P>
<P>        DateTime expiration = DateTime.Now.Add(this.CacheDuration);<BR>        HttpContext.Current.Cache.Add(Key, obj, null, expiration, TimeSpan.Zero, priority, null);<BR>    }</P>
<P>    public void ClearAll()<BR>    {<BR>        lock (syncObject)<BR>        {<BR>            foreach (string key in Keys)<BR>            {<BR>                HttpContext.Current.Cache.Remove(key);<BR>            }<BR>            Keys.Clear();<BR>        }<BR>    }</P>
<P>    public void Clear(string Key)<BR>    {<BR>        lock (syncObject)<BR>        {<BR>            if (Keys.Contains(Key))<BR>                Keys.Remove(Key);</P>
<P>            HttpContext.Current.Cache.Remove(Key);<BR>        }<BR>    }<BR>}<BR>
then to use it you do the following:
 return cacheManager.GetAndCheck<string>("somekey", delegate { return ExpensiveCall(); }); 
What do you guys think?

page 1 of 1
Comments: 0 | Views: 1215
Microsoft Communities