Tracking Dangling Object References In Silverlight

12 commentsWritten on August 4th, 2009 by
Categories: Memory Management, Silverlight

One of the downsides of working with a young platform like Silverlight is that the tool support isn't quite 'there' yet, particularly when it comes to profiling for performance and memory usage. And as you may or may not know, Silverlight makes it very easy to introduce memory leaks into your code. Since you can't just attach a memory profiler to your Silverlight application, optimizing memory usage or tracking down a leak can be a real pain in the ass.

In the past i have resorted to grabbing a memory dump of the browser and analyzing the content of the managed heap with windbg to track down which instances where being kept in memory. While this works, it's pretty time consuming and can quite easily lead you down the wrong path. One of the most important things that you want to know in this specific case is: which types are being kept in memory, and how many of them?

In this case, being able to query something during debugging regarding which instances are still kept alive in memory at certain times is sufficient for me. So i came up with the following class:

    public static class ObjectTracker

    {

        private static readonly object monitor = new object();

        private static readonly List<WeakReference> objects = new List<WeakReference>();

        private static bool? shouldTrack;

 

        public static void Track(object objectToTrack)

        {

            if (ShouldTrack())

            {

                lock (monitor)

                {

                    objects.Add(new WeakReference(objectToTrack));

                }

            }  

        }

 

        private static bool ShouldTrack()

        {

            if (shouldTrack == null)

            {

                shouldTrack = Debugger.IsAttached;

            }

 

            return shouldTrack.Value;

        }

 

        public static IEnumerable<object> GetAllLiveTrackedObjects()

        {

            lock (monitor)

            {

                GC.Collect();

                return objects.Where(o => o.IsAlive).Select(o => o.Target);

            }

        }

    }

The idea is basically to just keep a list of WeakReferences of objects you want to track (only if a debugger is attached), and later on you can 'query' the live instances through the GetAllLiveTrackedObjects method. This method obviously performs a full garbage collect to make sure only objects that are really still alive are returned. Again, you should almost never do a GC.Collect() manually, but in this case the method will only be called while you're debugging.

Then, you strategically put the following line in the constructor of every kind of type you'd like to track:

            ObjectTracker.Track(this);

I have that line in the constructor of my base View class, my base Controller class and in my base Disposable class. So now, when i want to check if there are any dangling references to instances of types that i really don't want hanging around, i can just do something like this:

            var liveObjects = ObjectTracker.GetAllLiveTrackedObjects();

 

            if (Debugger.IsAttached)

            {

                Debugger.Break();

            }

And then manually inspect the content of the liveObjects collection. It's far from perfect, but at least it's an easy way to at least know which instances (that i care about) are being kept in memory. It'll do until we get better tool support :p

  • Pingback: Reflective Perspective - Chris Alcock » The Morning Brew #405

  • Pingback: Finding Memory Leaks In Silverlight With WinDbg | The Inquisitive Coder – Davy Brion’s Blog

  • http://timcools.net Tim Cools

    Inventive debug tool!

    Side note: Although you made effort to synchronize the code, it seems that your code is not fully synchronized. The shouldTrack var in the ShouldTrack method can be initialized multiple times as long as the call is to Debugger.IsAttached not returned. Something you try to prevent by storing the value in a nullable field. You could use a double lock here to prevent this.

  • Pingback: DISCUSSIE Interactieve webapplicaties, welke technologie? - 9lives

  • Nike NFL Jerseys

    2011 Nike NFL Jerseys are a brand sale with fast deliver,and Cheap NFL Jerseys are favorite by many fans.

  • Red Bottom Shoes

    New Red Sole Heels are so charm at such low price, Cheap Red Sole Shoes are luxury and elegant when putting on them, you can’t resist the greatest discount of Red High Heels for women, 2011 shoes with Red Bottom Shoes show female’s gentle and beauty, and design Red Bottom Heels made by Louboutin Outlet show the beautiful shape of your legs.

  • Feijingjingseo

    Hydraulic oil, machinery oil, cooling oil
    lubricating oil during operation, volatile substances and impurities due to
    various reasons, will inevitably enter the lubrication,reduces the oil
    lubrication, heat dissipation, dispersion, cooling performance.  [url=http://www.chinahydraulicfilter.com/]Hydraulic
    oil filters[/url]using high quality filters, a large quantity of pollutants,
    high temperature and so on, [url=http://www.chinahydraulicfilter.com/p-Oil-filters-104317/Hydraulic-oil-filters-104320/]Hydraulic
    oil filter[/url] can quickly remove oil in the 
    impurity and volatile matter ( gasoline, diesel, kerosene and other),
    [url=http://www.chinahydraulicfilter.com/p-Compressor-filters-104375/Ingersoll-rand-filters-104376/]Ingersoll
    Rand filters[/url]uses the compact design, can also provide the best
    performance, but also improve oil quality, restore lubrication oil viscosity,
    flash point and the use of performance. Ensure that the hydraulic system, power
    system, lubrication system normal operation.

  • Anonymous

    Those high north face fleece jackets standards are the ones which result in
    cheap north face jackets, but it is those same standards which ensure that
    the north face sale remain available only to a select few.

  • Anonymous

    The north face sale has worked hard to build up a prestigious reputation of
    north face fleece, so now they want to keep the perception that a
    north face fleece jackets is more than just a jackets,

  • Anonymous

    The guess shoes new idea for the window display of the brand’s
    guess sale store in Paris has managed to make quite an impression.

  • Muhammad Tariq Muhammad Akram

    MyCarePharmacy.com is not an online pharmacy but an escrow service that connects you with a licensed pharmacy in a safe and trustworthy environment. If you are trying to find best online pharmacy then I think it is only one click far from you .

  • Pingback: bsnbsn.com