Posted by Davy Brion on July 14th, 2010
Actually, this time it’s pictures instead of just one… 2 of my coworkers pointed me to a piece of code that they thought was pretty ugly. Much to my amusement, i spotted something that i think is worth a post

This entry was posted on Wednesday, July 14th, 2010 at 3:53 pm and is filed under What's Wrong With This Picture.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
July 14th, 2010 at 4:04 pm
Nice, semi-weak reference
July 14th, 2010 at 4:16 pm
Looks like somebody missed the point of weak references…
July 14th, 2010 at 8:18 pm
This must be code someone wrote to test unexpected behavior occurring with a WeakReference, and then they accidentally never cleaned up the debugging cruft. I have a hard time believing someone would know enough about .NET to try using WeakReferences and then purposefully write code that fugly.
July 14th, 2010 at 8:20 pm
@Al
it’s in a core piece of Silverlight
that probably explains why there are so many memory leaks with Silverlight, no matter how hard you try to avoid them
July 14th, 2010 at 8:48 pm
That’s in Silverlight?! Gaaa.
I also enjoy that WeakRefSTRUCT, all protestations to the contrary, is not in fact a struct.
July 15th, 2010 at 11:33 am
What context was it in? You can sort of imagine someone thinking they wanted to retrieve value after weak reference has disappeared, even though weak reference can never be garbage collected because of the hard reference to value.
And why not use a struct? Mystifying.
July 15th, 2010 at 12:34 pm
@Rob Kent ‘What context was it in?’:
This piece of code can be found in the ‘LayoutUpdated’ event of ‘System.Windows.FrameworkElement’.
This event is actually a static event, but exposed as an instance event! The actual static list of handlers is of type ‘List’ and in addition to that the ‘FrameworkElement’-instance also keeps an instance of List with all of the attached eventhandlers.
To make it even stranger, this List is not kept as a normal instance field, but rather via a DependencyProperty (I have no idea why!).
Eventually when the event is raised (via unmanaged code) only the static ‘List’ is used. I guess that the actual reference of the eventhandler is also kept in memory to prevent that the “reference-tree” connected to the eventhandler is garbagecollected. This is probably done so to make it behave like a normal instance event instead of a static weak-event, so this means you have to remove/detach the eventhandler to prevent memory leaks (as in a normal event).
The ‘WeakRefSTRUCT’ is used as a helper to be able to remove an eventhandler from both the static and the instance lists more easily I guess.
This is my best guess as to why this ‘WeakRefSTRUCT’ thing is used, so I might be completely wrong about it.
Anyway you should take a look at the code in Reflector to view the entire ‘LayoutUpdated’ code.