WPF图像控制内存泄漏

我的程序有很多小图像(图像控件很小,而不是图像本身),并说了很多我的意思是超过500.这些图像是异步生成的,然后分配给之前初始化的Image控件。
基本上我的代码执行以下操作:

  filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("{0}.JPG", Guid.NewGuid().GetHashCode().ToString("x2"))); converter.ConvertPdfPageToImage(filename, i); //Fire the ThumbnailCreated event onThumbnailCreated(filename, (i - 1)); 

在创建图像的代码中没有内存泄漏,我有以下代码:

  string[] files = Directory.GetFiles("C:\\Users\\Daniel\\Pictures", "*.jpg"); for(int i=0; i<files.Length; i++){ onThumbnailCreated(files[i], i); } 

问题仍然存在。 这发生在事件处理程序方法中:

  void Thumbnails_ThumbnailCreated(ThumbnailCreatedEventArgs e, object sender) { //Since we generate the images async, we need to use Invoke this.parent.Dispatcher.Invoke(new SetImageDelegate(SetImage), e.Filename, e.PageNumber); } private void SetImage(string filename, int pageNumber) { BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); //I am trying to make the Image control use as less memory as possible //so I prevent caching bitmap.CacheOption = BitmapCacheOption.None; bitmap.UriSource = new Uri(filename); bitmap.EndInit(); //We set the bitmap as the source for the Image control //and show it to the user this.images[pageNumber].Source = bitmap; } 

有468个图像,程序使用大约1Gb的内存,然后根本就用完了。 我的任务甚至可以实现使用WPF还是图像数量太高? 也许我的代码有问题?
提前致谢

您应冻结这些图像 ,并将其宽度(或高度)设置为应用程序中实际使用的宽度(或高度) :

 // ... bitmap.DecodePixelWidth = 64; // "displayed" width, this improves memory usage bitmap.EndInit(); bitmap.Freeze(); this.images[pageNumber].Source = bitmap; 

试试这个:

 private void SetImage(string filename, int pageNumber) { using (BitmapImage bitmap = new BitmapImage()) { bitmap.BeginInit(); //I am trying to make the Image control use as less memory as possible //so I prevent caching bitmap.CacheOption = BitmapCacheOption.None; bitmap.UriSource = new Uri(filename); bitmap.EndInit(); this.images[pageNumber].Source = bitmap; } } 

当你完成它们时,这将处理你的位图。

它可能是导致内存泄漏的事件处理程序。

看到这个问题:

为什么以及如何避免事件处理程序内存泄漏?