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

Data receiving from multiple Serial Port in C#
C# Query an excel fastest method
WebView disable scrollbars
uwp - NullReferenceException thrown when upgrading UI control with bindings? [duplicate]
Linq Join Data Table to Entity Framework - Not Evaluating results
Generating Script from MDF database
trouble with use of functions of referenced project with custom config section
Is there a one line - condition check and code execution operator?
Building and refresh static list
Where does the x come from in this lambda expression? [duplicate]
C# Google Sheets APIv4 filling requestbody
Combobox in RowDetailTemplate update all before selected colums
Can we assign TextContext.TestDeploymentDir value to a static class data member?
Selenium InternetExplorerDriver on AppHarbor: Cannot start the driver service on localhost
C# Bitmap above Panel && Cursor position according to Panel
{C#}{SQL} Selecting from table and getting only 1 column

Categories

HOME
teradata
ide
intellij-idea
customization
cxf
mysqli
webvr
popover
google-docs-api
angularjs-directive
multipartform-data
install
handlebars.js
soap-client
osrm
fine-uploader
aggregate
infopath
internet-explorer-7
smooth-scrolling
virtuemart
airbnb
geography
hapijs
civicrm
serenity-js
ckeditor4.x
android-xml
priority-queue
oracle10g
windows-mobile
hierarchical-data
dynamic-memory-allocation
mplab
spring-oauth2
matlab-compiler
incapsula
observer-pattern
superclass
scrapinghub
spring-ide
serverless-architecture
text-formatting
jscoverage
dynamic-linking
sharpdevelop
aot
copy-constructor
easy68k
hotkeys
periodic-processing
dcast
oryx
android-togglebutton
page-flipping
vanilla-forums
properties-file
consul-template
android-networking
tidesdk
launcher
jsonmodel
mind-manager
conditional-comments
go-gin
tigase
pytz
telerik-appbuilder
hotlinking
.net-reflector
imaplib
nop
mobile-robots
violation
mandelbrot
mysql2
phone-state-listener
big-endian
google-email-audit-api
systrace
win-prolog
jmesa
stl-algorithm
windows-xp-embedded
functional-specifications
hwnd
xhtmlrenderer
response-time
llblgen
mediastreamsource
pitch-shifting
coderush-xpress
cross-cutting-concerns

Resources

Encrypt Message