What’s Wrong With This Picture?

7 commentsWritten on July 14th, 2010 by
Categories: What's Wrong With This Picture

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 :)

wr1

wr2

  • Adam

    Nice, semi-weak reference :D

  • Diego Mijelshon

    Looks like somebody missed the point of weak references…

  • Al

    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.

  • http://davybrion.com Davy Brion

    @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

  • http://machinedtolerance.blogspot.com Mark Knell

    That’s in Silverlight?! Gaaa.

    I also enjoy that WeakRefSTRUCT, all protestations to the contrary, is not in fact a struct.

  • http://www.proofbydesign.com/ Rob Kent

    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.

  • TomC

    @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.