當我將ListBox的ItemsSource綁定到List時,綁定引擎在控制消失後保留到列表元素上。這會導致所有列表元素留在內存中。使用ObservalbleCollection時問題消失。爲什麼會發生?綁定到列表導致內存泄漏
窗口標籤
<Grid>
<StackPanel>
<ContentControl Name="ContentControl">
<ListBox ItemsSource="{Binding List, Mode=TwoWay}" DisplayMemberPath="Name"/>
</ContentControl>
<Button Click="Button_Click">GC</Button>
</StackPanel>
</Grid>
後面的代碼裏面的XAML:
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.DataContext = null;
ContentControl.Content = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
視圖模型
class ViewModel : INotifyPropertyChanged
{
//Implementation of INotifyPropertyChanged ...
//Introducing ObservableCollection as type resolves the problem
private IEnumerable<Person> _list =
new List<Person> { new Person { Name = "one" }, new Person { Name = "two" } };
public IEnumerable<Person> List
{
get { return _list; }
set
{
_list = value;
RaisePropertyChanged("List");
}
}
class Person
{
public string Name { get; set; }
}
編輯:要檢查的人istances的漏水,我用螞蟻和.Net內存分析器。兩者都顯示按下GC按鈕後,只有綁定引擎持有對人物的引用。
你是什麼意思的「控制不見了」?它變得無形?它被卸載了嗎? – helb
你如何知道這裏的內存泄漏?你用什麼工具來描述這個? –
如何識別內存在使用List時發生泄漏。 –