c#


Memory leak in RenderTargetBitmap


I'm using a RenderTargetBitmap to render a set of controls in order to generate a PDF. The following code segment is the relevant section:
public Drawing.Image RenderPageBitmap()
{
RenderTargetBitmap bit = null;
Drawing.Bitmap bmp = null;
try
{
bit = new RenderTargetBitmap(ImageSource.PixelWidth, ImageSource.PixelHeight, 96, 96, PixelFormats.Pbgra32);
var viewBox = GetPageXaml(); //This method loads some prebuilt XAML from an embedded resource, setting the DataContext as needed.
var siz = new Size(bit.PixelWidth, bit.PixelHeight);
viewBox.Measure(siz);
viewBox.Arrange(new Rect(siz));
viewBox.UpdateLayout();
var draw = new DrawingVisual();
using (var graph = draw.RenderOpen())
graph.DrawRectangle(new BitmapCacheBrush(viewBox), null, new Rect(siz));
bit.Render(draw);
bit.Freeze();
bmp = new Drawing.Bitmap(bit.PixelWidth, bit.PixelHeight, Imaging.PixelFormat.Format32bppPArgb);
var data = bmp.LockBits(new Drawing.Rectangle(Drawing.Point.Empty, bmp.Size), ImageLockMode.WriteOnly, Imaging.PixelFormat.Format32bppPArgb);
{
bit.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
}
bmp.UnlockBits(data);
return bmp;
}
catch (Exception)
{
bmp?.Dispose();
throw;
}
finally
{
bit?.Clear();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
Even following other answers on StackOverflow and other forums (like clearing the bitmap and performing a garbage collection) doesn't seem to solve the issue. Each loop of this code can leak ~100MB of memory, which means I quickly hit the ~2GB limit of 32-bit processes.
The leak seems to occur on the RenderTargetBitmap.Render method exclusively, even the DrawingContext.DrawRectangle call doesn't noticeably increase memory usage.
Is there anything I can do to solve this problem?
You return the Bitmap to somewhere. Make sure you Dispose the Bitmap instance once you are done with it. What you are doing in the finally is useless when there is memory leak. If there are references GC wouldn't collect it.
Each loop of this code can leak ~100MB of memory, which means I
quickly hit the ~2GB limit of 32-bit processes.
Are you assuming there is a memory leak? May be there is no memory leak. I would get a good memory profiling tool and test this.
I have used ANTS Memory profiler and I find it good (it comes with 14 days trial). Just execute your logic a few times and see the Instance List if anything is growing. If so, look at the Retention graph to see what holds onto it. That will tell you what exactly happening. Root causes for memory leaks are quite difficult to guess sometimes, fortunately there are good tools for that.
Based on my inspection, draw allocates a DrawingVisual object.
Unless Render() frees it inside, you should explicitly delete the DrawingVisual object.

Related Links

Convert to sql query [closed]
GridView does not subscribe to CollectionChanged event
Having trouble calling a method from inside another method
How to disable beep in C# for Symbol PPT2800 barcode scanner?
How to find last used date for .mdb file in C# [closed]
Adding a parameter to a new eventhandler
EWS Search Calendar with Service Account
Use jQuery to delete a duplicate entry from table in database
Combobox filter on multiple properties
How to make Dynamic TextBox in C#
Change default date serialization in WCF
Why am I getting a corrupted ViewState error when I try and encasulate a 2D array inside a property to persist it between postbacks?
Are too many if else statements for validation bad? [closed]
C# Multiple Inheritance
Check that program logic is deterministic
Deploying my visual studio web application using IIS

Categories

HOME
msbuild
grizzly
intellij-idea
virtual-machine
blob
magento-1.9.2.1
ebay
msbi
schema
wavefront
sahi
software-collections
dcos
minimax
theory
unreal-engine4
aggregate
exchange-transport-agents
css-float
ibatis
indri
orange
sonarlint
summernote
turn.js
smali
tcpdf
scrapy-spider
utc
kundera
federated
vtd-xml
arp
urhosharp
choco
qt-designer
scene7
circle
gitosis
azure-vm-scale-set
maven-2
rythm
qt-quick
result
synchronized
qtwebkit
mef
activeandroid
g77
confluent
import.io
stanford-nlp-server
serialversionuid
openidm
audio-fingerprinting
node-java
dmalloc
grib
papyrus
dimensionality-reduction
xcode7.1
scriptengine
init
magick.net
php-java-bridge
avi
3d-rendering
abstract
commercetools
javapackager
libgcrypt
uinavigationitem
litedb
page-refresh
vectordrawable
firebase-tools
nexusdb
jad
cl.exe
optimistic-locking
scjp
power-management
.net-reflector
lastinsertid
randomaccessfile
grunt-contrib-imagemin
friendly-id
8-puzzle
violation
listpicker
gwt2
spawn
wxperl
eeprom
jqueryi-ui-buttonset
code-organization
isgl3d
javah
excellibrary
onunload
for-xml
pkcs#7
retrospectiva
cross-cutting-concerns

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile