I ran different tests recently on a .net app to see how memory footprint could be kept down. I came across various tips/guidelines like disposing unmanaged resources, unregistering events, using FREEZE on xaml resources etc. which all made sense. Most of the things were already taken care of , so the memory consumption remained same. I figured out however, that each new window which is never opened before in the current run, will consume some more memory and never seem to return it back after you close the window.
So I ran GC.Collect()right after the window close for debugging purpose but with no success.
In the app were a few windows with AllowsTransparency=true , so I removed the attribute and saw a big memory difference, approx.. 5MB less!, but whatever memory the window took now was still not released after the window was closed, so the problem remained the same. Here is the sample
C#
Window w;
bool isWindowOpen = false;
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!isWindowOpen)
{
w = new Window();
isWindowOpen = true;
// turn off the following two lines to see a noteable difference.
w.AllowsTransparency = true;
w.WindowStyle = WindowStyle.None;
//Even when the transparency is set to false, the memory increased by the new
//Window will never be returned. Try making the window a little bit heavier by
//adding a few buttons and combos and clicking them rapidly before closing the
//window.
w.Show();
}
else
{ w.Close(); isWindowOpen = false; GC.Collect();
//Console.WriteLine(GC.GetTotalMemory(true).ToString());
//Console.WriteLine(GC.CollectionCount(0).ToString());
}
}
Can any CLR/WPF guru please explain this? Is there absolutely no way I can force GC to run immediately after I close the transparent window, freeing up all the memory it consumed? I understand GC might run later when it needs to, but after all task manager is all what clients get, and there are some maniacs also.