title: WPF Image control memory leak
body: <p>My program has <em>a lot</em> of small images (Image controls are small, not the images themselves) and by saying a lot I mean more than 500. These images are generated asynchronously and then assigned to the <code>Image</code> controls, which were initialized before.<br>
  Basically my code does the following:</p>
  
  <pre><code>            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));  
  </code></pre>
  
  <p>There is no memory leak in code that creates the images, I have the following code:</p>
  
  <pre><code>            string[] files = Directory.GetFiles("C:\\Users\\Daniel\\Pictures", "*.jpg");
              for(int i=0; i&lt;files.Length; i++){
                  onThumbnailCreated(files[i], i);
              } 
  </code></pre>
  
  <p>Still the problem persists.
  This happens in the event handler method:</p>
  
  <pre><code>    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;
      }
  </code></pre>
  
  <p>With 468 images the program uses about 1Gb of memory and then runs out of it at all. Is my task even possible to achieve using WPF or is the number of images too high? Maybe there is something wrong with my code?<br>
  Thanks in advance </p>