Simple WPF sample causes uncontrolled memory growth

后端 未结 4 763
天命终不由人
天命终不由人 2021-02-02 16:49

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

4条回答
  •  -上瘾入骨i
    2021-02-02 17:36

    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.

提交回复
热议问题