I have boiled down an issue I\'m seeing in one of my applications to an incredibly simple reproduction sample. I need to know if there\'s something amiss or something I\'m missi
I was able to reproduce your problem using the code you provided. Memory keeps growing because the Canvas objects are never released; a memory profiler indicates that the Dispatcher's ContextLayoutManager is holding on to them all (so that it can invoke OnRenderSizeChanged when necessary).
It seems that a simple workaround is to add
c.UpdateLayout()
to the end of BuildCanvas
.
That said, note that Canvas
is a UIElement
; it's supposed to be used in UI. It's not designed to be used as an arbitrary drawing surface. As other commenters have already noted, the creation of thousands of Canvas objects may indicate a design flaw. I realise that your production code may be more complicated, but if it's just drawing simple shapes on a canvas, GDI+-based code (i.e., the System.Drawing classes) may be more appropriate.