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

Unit of work and general repository package
Getting version number from a running proccess ( With NO access to the .exe path)
How do I pass selectlist that is string to controller to save as a int value in asp.net mvc 5
WPF binding/display of different units
Unity - ensure that only one instance does the given command
Entity Framework Migrations not creating tables on database publishing
JSON format C# not generating all quotes the serializer
UWP: how to customize the app title
Crystal report SetParameterValue
Connecting Sphero & a Windows UWP app
How To Configure Multiple ISessionFactory in NHibernate?
Xamarin Button IsVisible Binding with ValueConverter not working
Unable to get TSC-TDP247 Printer Status from c#
passing a null value to the database from a dropdownlist in the form of boolean in c#
General function failure [Grid_266]
Sending Lotus Notes email through C# hiding SentBy field

Categories

HOME
postgresql
snappy
dronekit
bigtable
sitemap
yacc
annyang
segmentation-fault
coding-style
mongoimport
jpql
kairosdb
suitecrm
scotty
datasource
vala
typedef
lotusscript
multipart
infinite-loop
aws-iot
rvm
bootstrap-accordion
android-xml
grunt-contrib-uglify
datanucleus
knapsack-problem
visual-studio-community
utc
scripting-language
kundera
delphi-2010
concrete5
luhn
stencyl
pygraphviz
cowboy
julia-jump
mixed-models
ocamlbuild
togglebutton
jenkins-2
activeandroid
import.io
runtime-permissions
audio-fingerprinting
jenkins-docker
senti-wordnet
wicketstuff
was
cardview
glade
scriptengine
airwatch
hfp
window.location
clique
chomsky-normal-form
stdlist
wordpress-plugin
php-gd
lytro
personality-insights
alpha-beta-pruning
drawable
visual-c#-express-2010
xpand
pyalgotrade
visual-studio-setup-proje
.net-reflector
static-class
kohana-orm
playing-cards
qgraphicsscene
backbone-views
metapost
invalidoperationexception
gssapi
databus
android-memory
sup
jmesa
advanceddatagrid
code-organization
isgl3d
auto-compile
azure-appfabric
s60
xcdatamodel
iphone-maps
database-agnostic
jquery-attributes
silverlight-2.0
code-golf
datadude
data-formats
manuals
content-delivery-network
disk-based

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App