views:

1737

answers:

2
+2  Q: 

Weak references

can someone explain the main benefits of different types of references in C#, weak references, soft references, phantom references, strong references.

We have an application that is consuming a lot of memory and we are trying to determine if this is an area to focus on.

+8  A: 

Soft and phantom references come from Java, I believe. A long weak reference (pass true to C#'s WeakReference constructor) might be considered similar to Java's PhantomReference. If there is an analog to SoftReference in C#, I don't know what it is.

Weak references do not extend the lifespan of an object, thus allowing it to be garbage collected once all strong references have gone out of scope. They can be useful for holding on to large objects that are expensive to initialize but should be avaialble for garabage collection if they are not actively in use.

Whether or not this will be useful in reducing the memory consumption of your application will depend completely on the specifics of the application. For example, if you have a moderate number of cached objects hanging around which may or may not be reused in the future, weak references could help improve the memory consumption of the caches. However, if the app is working with a verly large number of small objects, weak references will make the problem worse since the reference objects will take up as much or more memory.

Scott Pedersen
+5  A: 

MSDN has a good explanation of weak references. The key quote is at the bottom where it says:

Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects.

Every time I've seen a WeakReference in the wild, it's been used as an automatic solution to memory management problems. There are likely better solutions to your application's problems.

MusiGenesis