Why I used the MappedImage object would lead to memory leak using C# programming?

Dear all,
I have a question on MappedImage object in C# language.
My aim is crop the rect of source image.
the function of MappedImage is effective, but the pc memory keeps increasing.
Would you tell me why the pc memory is increasing?
Thanks every all.

My demo is below:

    using (Stemmer.Cvb.Image img = Stemmer.Cvb.Image.FromFile("xxx.bmp"))
    {
        Point2D pt = new Point2D(0, 0); 
        Size2D imgSize = img.Size;
        Rect re = new Rect(pt, imgSize);
        using (MappedImage mapImg = img.Map(re) )
        {
            pt = Point2D.Empty;
            re = Rect.Empty;
            img.Dispose();
            mapImg.Dispose();
        }
    }
    System.GC.Collect();
    GC.WaitForPendingFinalizers();

Hi @JieZhao

I couldn’t reproduce your result with the Stemmer.Cvb.dll version 1.30. I used Visual Studio’s internal reporting and Microsoft’s Process Explorer. I used a slightly different test (I explain why below):

static void Main(string[] args)
{
  Console.WriteLine("Hit key to start...");
  Console.ReadKey();
  Console.WriteLine("running...");

  var imagePath = Path.Combine(SystemInfo.InstallPath, "Tutorial", "FruitBowl.jpg");
  foreach (var iteration in Enumerable.Range(0, 1000))
  {
    using (var fruitBowl = Image.FromFile(imagePath))
    {
      using (var map = fruitBowl.Map(fruitBowl.Bounds))
      {
        Debug.Assert(map.Size == fruitBowl.Size);
      }
    }
  }

  Console.WriteLine("done...");
  Console.ReadKey();
}

Here is the result from the internal reporting:
image

And Process Explorer’s start and end (at the .ReadKey() calls):

I changed your test a bit as you have double-dispose in it. The using-block also calls dispose. The GC.Collect also has no real impact as you disposed the images which frees the native image buffer memory.

The interesting section is Virtual Memory and there Private Bytes/Peak Private Bytes. The increase from the first snap shot by ~1MB is due to loaded modules (DLLs). The peak is ~4MB larger which is roughly the image memory. The memory usage by the MappedImage is insignificant as its only a view on the original’s image’s. The effects are the same for .bmp files – I used fruit bowl as it has a larger and thus more visible memory footprint.

1 Like