【发布时间】:2010-03-29 22:31:31
【问题描述】:
更新:我在另一台安装得更干净的机器上尝试了这个。我无法在那台机器上重现这个。如果我找出是什么有问题的 (VSStudio) 组件导致了这种情况,我会告诉你的。
我从后面的代码创建了一些 UIElements,并期待垃圾收集来清理东西。但是,这些对象在我预期的时候并没有被释放。我期待它们在 RemoveAt(0) 处被释放,但它们仅在程序结束时被释放。
如何使对象从 Canvas 的 Children 集合中被释放?
<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>
后面的代码是:
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.Add(new MyControl() { Background = Brushes.Yellow, Width = 100, Height = 50 });
else
main.Children.RemoveAt(0);
}
}
public class MyControl : UserControl
{
~MyControl()
{
Debug.WriteLine("Goodbye");
}
}
【问题讨论】:
标签: .net wpf memory-management garbage-collection