DependencyProperty内存泄漏

Guy*_*Guy 4 c# wpf c#-4.0

我正在使用PerfView来发现内存泄漏。

在比较两个快照之后,我注意到PerView中的RefTree-> static vars选项卡下。 MyPageDependencyProperty的矿占公司总收益的78.9%。

MyPageDependencyProperty不应该在那里,因为我关上了XAML窗口是属于。

我不使用AddValueChanged它会导致内存泄漏。

DependencyProperty揭示 ObservableCollection<object>

有谁知道我可以解决这个问题吗?

谢谢

dev*_*hog 5

而不是像这样定义您的属性,这会创建一个静态的ObservableCollection。

public static readonly DependencyProperty SomePropertyProperty  = DependencyProperty.Register(typeof(..), typeof(..),....,.... , new ObservableCollection<...>());
Run Code Online (Sandbox Code Playgroud)

你应该做这个:

public static readonly DependencyProperty SomePropertyProperty = DependencyProperty.Register(typeof(..), typeof(..),...., null);

public MyControl()
{
   this.SomeProperty = new ObservableCollection<...>();
}
Run Code Online (Sandbox Code Playgroud)

您的问题将神奇地消失。:)