views:

258

answers:

4

I am familiar with WeakReference, but I am looking for a reference type that is cleared only when memory is low, not simply every time when the gc runs (just like Java's SoftReference). I'm looking for a way to implement a memory-sensitive cache.

+1  A: 

No there isn't an equivalent. Is there a particular reason why WeakReference won't do the job?

Here is a similar question to yours:

http://stackoverflow.com/questions/324633/why-doesnt-net-have-a-softreference-as-well-as-a-weakreference-like-java

Andrew Hare
+1  A: 

Maybe the ASP.NET Cache class (System.Web.Caching.Cache) might help achieve what you want? It automatically remove objects if memory gets low:

Here's an article that shows how to use the Cache class in a windows forms application.

M4N
+1  A: 

In addition to the ASP.NET Cache, there is the Caching Application Block from the Microsoft Patterns and Practices group.

http://msdn.microsoft.com/en-us/library/cc309502.aspx

Rob Windsor
A: 

The ASP.NET cache gives you the memory-sensitive behaviour you want, with the drawback that everything needs a unique key. However, you should be able to hold a WeakReference to an object that you've placed in the ASP.NET cache. The cache's strong reference will keep the GC at bay until the cache decides that it needs to be scavenged to free memory. The WeakReference gives you access to the object without doing a lookup with the cache key.

Foo cachedData = new Foo();
WeakReference weakRef = new WeakReference( cachedData );
HttpRuntime.Cache[Guid.NewGuid().ToString()] = cachedData;

...

if ( weakRef.IsAlive )
{
    Foo strongRef = weakRef.Target as Foo;
}

You could create a SoftReference class by extending WeakReference along the lines of

class SoftReference : WeakReference
{
    public SoftReference( object target ) : base( target )
    {
        HttpRuntime.Cache[Guid.NewGuid().ToString()] = target; 
    }
}

You'd also need to override the setter on Target to make sure that any new target goes into the cache.

stevemegson