Weak reference benefits

C#WinformsMemoryReferenceWeak References

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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 available for garbage 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 that 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 very large number of small objects, weak references will make the problem worse since the reference objects will take up as much or more memory.

Solution 2 - C#

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.

Solution 3 - C#

Brilliant real example with WeakReference is explained in Android development tutorial.

There is an image (Bitmap) and image container on the view (ImageView). If image will be loaded not from memory (but e.g. from disk, net) then it can lock UI thread and the screen. To avoid it an async task can be used.

The problem arises when async task finishes. Image container can be not useful at all at that time (screen is changed or Android unloads invisible view part after scrolling). WeakReference can help here and ImageView will be garbage collected.

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;

    public BitmapWorkerTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }
    // Method for getting bitmap is removed for code clearness

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}

P.S. the example is in Java, but can be understood by C# developers.
Source: http://developersdev.blogspot.ru/2014/01/weakreference-example.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#Scott PedersenView Answer on Stackoverflow
Solution 2 - C#MusiGenesisView Answer on Stackoverflow
Solution 3 - C#Artur AView Answer on Stackoverflow