Windows Phone 7 Appstore: Submission in progress

by Kurt Evenepoel 18 January 2011 21:52

Note to beginning submitters: "submission in progress" is the stage that precedes "testing in progress".  If you stay on that for too long, return and check if youve clicked "submit now", otherwise you can wait for a very long time!

Weak references in C#

by Kurt Evenepoel 6 January 2011 13:53

To start the story off, let’s examine how a normal reference works:
[code:c#]public class Circle
    public double Radius { get; set; }

Circle circle = new Circle();
Circle theSameCircle = circle;[/code]

In this example, we assign a reference pointing to an already existing circle to the variable “anotherCircle”.

When the variable “circle” goes out of scope, does this mean the Circle object is eligible for garbage collection?
The reference to the created Circle is removed, but the variable “anotherCircle” still holds a reference to it.  The created Circle object is not eligible until the last reference to it has gone (or is out of scope), in this case the “anotherCircle” variable is preventing the object from being garbage collected. You could say that in this scenario, both “circle” and “anotherCircle” share responsibility over the Circle variable in terms of existance.

You may wonder, “Why is this important? When they’re both gone they get garbage collected anyway.”  That is not really the point.  The point is that, while not necessarily important in every case, the distinction is similar to the difference in composition and aggregation in UML: a strong reference is a ‘strong link’ and a weak reference a ‘weak link’, similar to how composition and aggregation differ from one another.  Theyre not really the same thing, but maybe you see my point: a ‘strong link’ assumes some responsibility over the object (in this case, keeping it alive), a ‘weak link’ assumes that another else has the ‘keep alive’ responsibility over the object, which is similar to the concept of programming C++ where theres always one object responsible for the cleanup of the another object. Except there it's more active.  In .NET memory gets cleaned up regardless, just when and how efficiently is something you can control with classes like WeakReference.

In the case of UML’s composition, a child part cannot exist without the parent part.  With aggregation, both parts can exist independantly.  Does it make sense then for the child part to prevent the parent from being garbage collected (if the programmer using your API retains a reference to the child part, the parent part is kept in memory)?  Ofcourse not, in most scenarios if the programmer wants to work with the wheel of a car and doesn’t keep the car in memory himself, he just wants to work with the wheel, if he wanted to work with the car he’d have kept the car.   Unless the wheel has a ‘Car’ or ‘Parent’ public property, the developer has no way of knowing your internal implementation references the car. Enter the WeakReference class.

A weak reference is a reference that does not keep the referenced object alive.  This is especially handy for circular references (where objects keep themselves alive and need extra work by the garbage collector to detect they’re actually both dead instead, for example a an item in a list that also references the list it’s in).   In terms of cleanup it is many times faster, and it relinquishes the responsibility of keeping the object alive to another object, meaning that a weak reference does not prevent garbage collection.  If the programmer lets the referenced object go out of scope and does not retain their own reference to it, the object will be garbage collected.
So how does this work?

If the object has been garbage collected, the WeakReference’s Target property returns null.  Therefore, you need to check if the target is null before use.
Maybe the following class will make it easier for you:

[code:c#]public class WeakReference<T>: WeakReference
        where T: class
        public WeakReference(T target): base(target)
        public new T Target
                return (T)base.Target;
                base.Target = value;

        public static implicit operator T(WeakReference<T> reference)
            return reference.Target;


A nice thing about a WeakReference is that you’re absolutely sure you don’t have to call Dispose or do anything with the IDisposable interface.  If it’s IDisposable, its someone else’s responsibility to dispose, not the WeakReference’s.  Therefore, a weak reference adds to clarity when it comes to disposable types that are supposed to be cleaned up elsewhere (very useful in template methods for example)
On top of that, a WeakReference to an IDisposable is not disposable, so the class that holds member variables that are WeakReferences to IDisposable types do not need to be IDisposable themselves (I’m looking at users of Code Analysis or FXCop), which is a large bonus.

Let me show you another example:

[code:c#]List circleList = new List<Circle>();
circleList.Add(new Circle());[/code]

In this example, we have a list and we’ve added a new circle object to it.  Do you expect the list to be responsible for retaining the circles?  Yes, obviously you do, you do not want to hold a reference to every circle in the list you created like this:

[code:c#]Circle circle1 = new Circle();
Circle circle2 = new Circle();

That would be very tiresome.  Lists, dictionaries, normal variable assignments: they’re all strong references.  Strong references prevent garbage collection, and therefore take or share ownership of an object.  But that’s not always what you want.  A perfect example where you could use weak references would be an observer/observable system or events.  You would not want to keep every and any object in memory just because they have attached an event, right?  If they’d forget to remove the event handler, the object instance would remain in memory forever.  In this case, you’d prefer to have it turned to ‘null’ automatically and check for null before calling anything on the object.  Which is exactly what a WeakReference does.

Can't find MVC2 templates?

by Kurt Evenepoel 6 January 2011 11:14

Then you may have had the same issue i did: the MVC2 project templates did not show up in the "add new project" list, they only show up in the "create new project" list.  Just create the project like that and then add the newly created project as an existing project to your solution.  Happy MVC'ing.

Tags: ,


About me

I've started my company called 'Mad Savant'.  We focus on world domination. Holding multiple MCPD's and passionate about .NET, Microsoft in general, patterns, practises and writing quality software, I'm an experienced senior developer and fledgeling architect, having over 4j experience in .NET and over 10y development experience in total.

Other pages