Which reference keeps my object alive?

Use this forum for questions on how to use .NET Memory Profiler and how to analyse memory usage.
Post Reply
MTR

Which reference keeps my object alive?

Post by MTR » Thu Nov 10, 2011 1:36 pm

Hello,
I have a really huge/complicated object which doesn't get garbage collected.
My test application looks like this:

Code: Select all

        List<WeakReference> Referenzen = new List<WeakReference>();

        private void Button_New(object sender, RoutedEventArgs e)
        {
            Referenzen.Add(new WeakReference(new MyHugeObject()));
        }

        private void Button_Check(object sender, RoutedEventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            int AliveCounter = 0;
            foreach (var item in Referenzen)
            {
                if (item.IsAlive)
                {
                    AliveCounter++;
                    Debug.WriteLine("Object " + item.Target.GetType().ToString() + " lives!");
                }
            }
            if (AliveCounter > 0)
            {
                MessageBox.Show(AliveCounter.ToString() + " objects still alive!");
            }
       }
I press the new button and then the check button and see that my object is still alive.

Using Memory Profiler I see that there are 61 references to this object, but none of them is from my own code.

To be more specific, this object is from a college and is a WPF/XAML usercontrol with some child controls.

Is there a way to detect, which of these 61 references, which come somewhere out of the WPF/XAML framework, is preventing the GC from deleting this object?

Andreas Suurkuusk
Posts: 1029
Joined: Wed Mar 02, 2005 7:53 pm

Re: Which reference keeps my object alive?

Post by Andreas Suurkuusk » Fri Nov 11, 2011 4:58 pm

The root paths and the instance graph of an instance will tell you which references keep your instance alive. I recommend that you take a look at the instance graph, because it makes it easier to get an understanding of how an instance is rooted. You can get a little more information about the instance graph on our website, and in the online documentation.
Best regards,

Andreas Suurkuusk
SciTech Software AB

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 28 guests