一个简单的WPF应用程序中的非托管泄漏

当鼠标移动到我的WPF应用程序上时,我遇到了泄漏非托管内存的情况。 具体来说,当我在perfmon或Red Gate的内存分析器中分析应用程序时,私有字节会单调增加,但所有托管堆中的字节保持不变 – 我相信,这意味着应用程序具有非托管泄漏。

我创建了一个简单的repro应用程序,但我看不出问题出在哪里。

该应用程序包含一个包含四个项目的ListView。 在这些项目上快速移动鼠标会导致问题。

如果你有兴趣重现这个问题,这是代码 – 它不漂亮,但它很简单。

谢谢


编辑:我已为此问题创建了Microsoft Connect问题。


App.xaml中

          

App.xaml.cs

 using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace WpfLeakRepro { ///  /// Interaction logic for App.xaml ///  public partial class App : Application { } } 

Generic.xaml

                                          

Window1.xaml

                           

Window1.xaml.cs

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.ComponentModel; using System.Collections.ObjectModel; using System.IO; namespace WpfLeakRepro { public class Picture { public string Name { get; set; } } ///  /// Interaction logic for Window1.xaml ///  public partial class Window1 : Window { public Window1() { InitializeComponent(); List pictures = new List(); string[] images = new string[] {"Blue hills.jpg", "Sunset.jpg", "Water lilies.jpg", "Winter.jpg" }; foreach (string imagePath in images) { pictures.Add(new Picture() { Name = imagePath }); } DataContext = pictures; } } } 

您可能在WPF绑定中创建了已知的内存泄漏,这可能在绑定到未实现INotifyPropertyChanged的类的属性时发生。 在您的情况下, Picture类的Name属性。

解决方案是将绑定模式设置为OneTime,让Picture实现INotifyPropertyChanged或将Name为依赖项属性。

从ms支持和这篇博客文章中了解更多相关信息 。 这些和其他已知的WPF内存泄漏可以在这里找到。

该问题似乎与用于方格背景的VisualBrush有关。 用SolidColorBrush替换它,问题就消失了。 但它确实没关系:微软的人建议我安装最新升级到.NetFx 3.5sp1,这似乎解决了这个问题( 这里有更多细节)。