Standing on the shoulders of giants. RSS 2.0
# Sunday, March 04, 2007

Although generally a bad idea [0], there is another problem. The System.Web.Caching.Cache doesn't call dispose on the items removed from the cache, causing a resource leak. To prevent this resource leak, add a CacheItemRemovedCallback in which you dispose of the object.

 

// add the item to the cache, note the callback

HttpRuntime.Cache.Add("myKey", myClass, null, DateTime.Now.AddSeconds(5), 
     Cache.NoSlidingExpiration, CacheItemPriority.Default, 
     new CacheItemRemovedCallback( OnRemoved ) );

// callback function

void OnRemoved( string key, object value, CacheItemRemovedReason reason ) {

     IDisposable disposable = value as IDisposable;
     if (disposable != null) {
          disposable.Dispose();
     }
}

 

[0] Should you really be caching an object containing unmanaged resources, which usually are scarce?

Sunday, March 04, 2007 5:58:57 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] - Trackback
Codesnippet | C#
Comments are closed.
About
© Copyright 2008
Paul van Brenk
Sign In
newtelligence dasBlog 2.3.8275.16006
All Content © 2008, Paul van Brenk
DasBlog theme 'Business' created by Christoph De Baene (delarou)