开发者

In WPF: Children.Remove or Children.Clear doesn't free objects

Update: I tried this on another, more cleanly installed, machine. I could not reproduce this on that machine. If I find out what offending (VSStudio) component causes this, I will let you know.

I create some UIElements from code behind and was anticipating the garbage collection to clear up stuff. However, the objects are not free-ed at the time I expected it. I was expecting them to be freeed at RemoveAt(0), but they are only freed at the end of the program.

How can I make the objects be freed when removed from the Children collection of the Canvas?

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
    MouseDown="Window_MouseDown">
  <Grid>
    <Canvas x:Name="main" />
  </Grid>
</Window>

The code behind is:

public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();
  }

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
  GC.Collect(); // This should pick up the control removed at a previous MouseDown
  GC.WaitForPendingFinalizers(); // Doesn't help either

  if (main.Children.Count == 0)
    main.Children开发者_StackOverflow社区.Add(new MyControl() { Background = Brushes.Yellow, Width = 100, Height = 50 });
  else
    main.Children.RemoveAt(0);
 }
}

public class MyControl : UserControl
{
  ~MyControl()
  {
    Debug.WriteLine("Goodbye");
  }
}


Change

public class MyControl : UserControl

to

public class MyControl : ContentControl

and it will say goodbye (after the second time you remove the control.) I also verified the memory does not leak by using

Debug.WriteLine("mem: " + GC.GetTotalMemory(true).ToString());

Also, see this:

You remove the TestControl by clearing grid.Children, but it is not immediately eligible for garbage collection. Several asynchronous operations on it are pending, and it cannot be GC'd until those operations complete (these include raising the Unloaded event and some cleanup code in the rendering engine).

I verified that if you wait until these operations complete (say by scheduling a Dispatcher operation at ContextIdle priority), the TestControl becomes eligible for GC, independent of the presence of a binding on the TextBlock.

UserControl must either have a internal event that doesn't clean up quickly, or it might be a bug with VS2010 RC. I'd report this through connect, but for now switch to ContentControl.

Since you're using UserControl, I assume you'll also have to switch to using the Generic.xaml template. That isn't too difficult of a change-over (and for most things is a better solution.)


You may find this of interest. I found out recently that x:Name markup extension stores a reference to the UIElement in the parent control in a dictionary keyed by the string name.

When you remove the UIElement from its parent, the dictionary keeps a reference to the control.

There's a blog post / video debugging the memory leak here: WPF x:Name Memory Leak

The solution is to not use x:Name or to ensure that controls that are kept alive by x:Name are cleared out so as not to consume too much memory before a section of the visual tree is collected.

Update: You deregister a named class using the NameScope

this.grid.Children.Remove(child); // Remove the child from visual tree
NameScope.GetNameScope(this).UnregisterName("child"); // remove the keyed name
this.child = null; // null the field

// Finally it is free to be collected! 


There are 3 generations of garbage collection in C#, so even if there are no references to your objects, it could take 3 garbage collections to free them.

You can use the GC.Collect()'s parameter to force a 3rd generation garbage collection,
however, the best approuch is to not call GC.Collect() yourself,
instead use the IDisposable interface and bind the Children to an ObservableCollection and when you get a CollectionChanged event Dispose() of any removed objects.


Objects in C# are not automatically "freed" as soon as they are no longer used.

Rather, when you remove the object from your Control, it becomes eligible for garbage collection at that point, assuming you have no other references to that UIelement.

Once an object is "unrooted" (there are no references, directly or indirectly, from any used object in your application), it becomes eligible for collection. The garbage collector will then, eventually, clean up your object, but when this happens is not something you (typically) control.

Just trust that it will eventually get cleaned up. This is the beauty of C# (and .NET in general) - the management, and worry, of this is handled for you.


Edit: After some testing, it appears that the Window holds a reference to the UIelement until the next layout pass. You can force this to occur by adding a call to:

this.UpdateLayout();

After removing the element(s) from the canvas Children. This will cause the objects to be available for GC.


We had the same problem and also thought that this may be the reason. But we analyzed our project using Memory profiler tools and found that there is nothing to do with the Grid.Remove or Grid.RemoveAt. So i think my suggestion is just have a look your project at the memory profiler tool and see what is happening inside your project. hopes this helps.


I think that the answer by Reed Copsey was most directly on the mark as to the explanation of the behavior the OP had seen.

Here's a modified program which does, in fact, behave exactly as the OP seemed to expect.

The differences from the original are:

  • Calls UpdateLayout() to make sure the effect of removing the control from the layout system has been realized.

  • Waits for the Dispatcher to complete any pending processing (without this the exact timing of the user control finalization could vary and might occur in a later GC call than expected).

  • Does a second GC Collect and a WaitForFullGCComplete to make sure the GC really has had a chance to do its job.

 

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (main.Children.Count == 0)
    {
        Console.WriteLine("Adding control");
        main.Children.Add(new MyControl() { Background = Brushes.Yellow, Width = 100, Height = 50 });
    }
    else
    {
        Console.WriteLine("Removing control");
        main.Children.RemoveAt(0);
    }

    UpdateLayout();
    Dispatcher.Invoke(new Action(() => { }), System.Windows.Threading.DispatcherPriority.ContextIdle, null);

    GC.Collect(); // This should pick up the control removed at a previous MouseDown
    GC.WaitForPendingFinalizers(); // Doesn't help either
    GC.Collect();
    GC.WaitForFullGCComplete();
}

The output I get in both debug & release builds is:

Adding control
Removing control
Goodbye
Adding control
Removing control
Goodbye
Adding control
Removing control
Goodbye
...

I think this does in fact demonstrate that the garbage collection is working as it is supposed to.

Regarding the note that the OP saw different behavior on different PCs - well who knows if that could have been some bug in 2010, but I suspect it was just that different PCs had different loads and this affected something about the GC processing.

I tested using .NET framework 4.7.2 in VS2019.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜