Rob*_*ner 5 wpf garbage-collection memory-leaks
我们的应用程序从它的主窗口中添加和删除 WPF (4.0) UserControls,我们注意到它们没有收集垃圾(通过从不返回 null 的 WeakReferences)。似乎如果 UserControl 具有绑定,即使从未将控件添加到树中,也会发生这种情况。控制台应用程序中最简单的复制如下:
主程序
class Program
{
[STAThread]
static void Main(string[] args)
{
var obj = GetObj();
var ctl = GetCtl();
for (int x = 0; x < 4; x++)
{
GC.Collect();
Thread.Sleep(1000);
}
bool objAlive = obj.IsAlive;
bool ctlAlive = ctl.IsAlive;
Console.WriteLine(objAlive + "-" + ctlAlive);
Console.ReadLine();
}
private static WeakReference GetObj()
{
return new WeakReference(new object());
}
private static WeakReference GetCtl()
{
return new WeakReference(new MyCtl());
}
}
Run Code Online (Sandbox Code Playgroud)
MyCtl 用户控件(后面的代码是标准的,没有被修改
<UserControl <!--Snip Default Namespaces-->>
<TextBlock Text="{Binding Blah}" />
</UserControl>
Run Code Online (Sandbox Code Playgroud)
objAlive 为假,但 ctlAlive 为真。如果从 UserControl XAML 中删除了 Binding,则两者都为 false。如果我连接内存分析器,MyCtl 仍然存在,但我无法弄清楚引用它的是什么(有关如何使用 jetBrains 找到它的提示值得赞赏)。
这是预期的行为还是我需要做更多的事情来清理我的 WPF UserControls?
取决于你要绑定什么。
这可能是一个已知问题: http ://support.microsoft.com/kb/938416
您是否绑定到自定义类?您是否实现了 INotifyPropertyChanged 或创建了 DependencyProperty?