I have a WPF that leaks a lot of memory calling RenderTargetBitmap.Render. I see posts all over the internet about how this was supposed to be fixed but isn't. I have done a lot of looking but can't find a workaround. This is .net 3.5 sp1
I subclassed the inkCanvas object to handle multi-page tiffs. I save each page as a bitmapImage in an array. I also save a corresponding StrokesCollection array. When it is time to save the multi-tiff I call a method called BindImage that loads the image and corresponding StrokesCollection into the canvas and saves it as a page of a tiff.
the line:
rtb.Render(this);
leaks memory at each page iteration. My code works well with smaller tiffs, but those with many pages cause OutOfMemoryException.
I have tried:
-recompiling under .net 4
-creating a new inkcanvas on the fly, then calling render on it and destroying it, then calling carbage collection.
private void BindImage()
{
System.Windows.Controls.Image imgTemp;
bmpSavePages = new BitmapImage[bmpPages.Length];
for (int i = 0; i < bmpPages.Length; i++)
{
this.Children.Clear();
this.Strokes.Clear();
imgTemp = new System.Windows.Controls.Image();
imgTemp.Source = bmpPages[i];
this.Children.Add(imgTemp);
this.Strokes.Add(strWriting[i]);
this.Children[0].UpdateLayout();
MemoryStream ms = new MemoryStream();
RenderTargetBitmap rtb = new RenderTargetBitmap((int)dbImageWidth, (int)dbImageHeight, dbPixelWidth, dbPixelDepth, pxfFormat);
rtb.Render(this);
BitmapEncoder encoder = new TiffBitmapEncoder();
try
{
encoder.Frames.Add(BitmapFrame.Create(rtb));
encoder.Save(ms);
bmpSavePages[i] = new BitmapImage();
bmpSavePages[i].BeginInit();
bmpSavePages[i].StreamSource = ms;
bmpSavePages[i].CacheOption = BitmapCacheOption.OnLoad;
bmpSavePages[i].DecodePixelHeight = (int)dbImageHeight;
bmpSavePages[i].EndInit();
}
catch (Exception e)
{
System.Windows.MessageBox.Show("There was an error binding the final image.\n\n" + e.Message);
}
finally
{
ms.Dispose();
ms = null;
}
}
}