How to Free RAM at Silverlight/WPF ? I define a UserControl MyUC that has a Image and three Textblock. I add 10000 MyUCs to a Grid, then clear the Grid’s Children,but RAM is not Freed! Why?
MyUC:
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="32"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{Binding ICO}" Width="32" Height="32"/>
<StackPanel Grid.Column="1" Orientation="Vertical" Width="359" Margin="0,0,-189,0">
<TextBlock Text="{Binding ID}"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding URL}"/>
</StackPanel>
</Grid>
Code:
MyUC uc = null;
for (int i = 0; i < 10000; i++)
{
uc = new MyUC();
this.LayoutRoot.Children.Clear();
this.LayoutRoot.Children.Add(uc);
}
Help me? 3KS!
The short answer is you don’t do anything explicit to release memory in the case you have provided.
As each instance of your MyUC class goes out of scope, the Garbage Collector will determine that it is no longer reachable. At the next garbage collection, the unreachable instances will be ‘marked’ and the memory will be compacted. It’s all fundamental to how .NET works.
Whether or not your diagnostic for measuring memory is detecting the effects of garbage collection is another story, and you didn’t provide any info on what diagnostics you are using.
Garbage collection in the Microsoft .NET common language runtime environment completely absolves the developer from tracking memory usage and knowing when to free memory. However, you’ll want to understand how it works. Part 1 of this two-part article on .NET garbage collection
Source: Jeffery Richter Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework