更新:我在另一個更乾淨的機器上試過這個。我無法在該機器上重現這一點。如果我發現哪些違規(VSStudio)組件會導致此問題,我會通知您。在WPF:Children.Remove或Children.Clear不會釋放對象
我從後面的代碼創建了一些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>
後面的代碼是:在C#
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");
}
}
我知道,註銷已命名的類,但不這麼認爲在這種情況下。當我在MouseDown處理程序的開頭添加GC.Collect()時,它應該選擇符合垃圾收集條件的控件。它沒有。我收集的內容仍然必須在Canvas對象內部引用它。 – 2010-03-29 22:47:23
@Bart:嘗試在處理程序的END處添加GC.Collection - 控件仍處於處理程序開始處的UI中...是否有幫助? – 2010-03-29 22:48:32
@Bart:另外 - 嘗試添加對GC.WaitForPendingFinalizers()的調用 - 請參閱:http://msdn.microsoft.com/en-us/library/system.gc.waitforpendingfinalizers.aspx – 2010-03-29 22:49:49