首页 > 解决方案 > 与 CanvasControl 相关的奇怪内存泄漏

问题描述

我设法在一个非常小的测试项目中隔离了一个奇怪的问题。所有代码都在下面的代码隐藏中。

要点是,如果在按下按钮时,我将 MainGrid 内容替换为新网格,并将新的 CanvasControl 添加到该辅助新网格,我不会出现内存泄漏。

但是,如果我替换了继承 Grid 的 CanvasInGrid 对象,并将画布添加到它自己的内容中,则每次按下按钮时,CanvasInGrid 和 CanvasControl 的对象计数都会增加,如诊断工具/内存使用/拍摄快照所示

但是,如果我在 CanvasInGrid 中添加一个按钮,则再次没有内存泄漏。

我只能将其视为 CanvasControl 中的错误?还是我错过了什么?以这种方式添加画布控件时,是否有一种安全的方法可以防止此问题?

即使我抓住 CanvasInGrid_Unloaded 并设置 Canvas = nothing,Canvas 数量似乎也没有增加,但我得到了一些其他的东西,包括 CanvasInGrid:

内部指针 +1 +12 +12 12 144 144

条件弱表 +1 +32 +216 12 384 2,592

条件弱表+容器 +1 +184 +184 12 2,208 2,208

WindowsRuntimeMarshal+NativeOrStaticEventRegistrationImpl+TokenListCount +1 +20 +20 12 240 240

WindowsRuntimeMarshal+NativeOrStaticEventRegistrationImpl+EventRegistrationTokenListWithCount +1 +24 +24 12 288 288

App1.CanvasInGrid +1 +20 +20 6 120 144

Public NotInheritable Class MainPage
    Inherits Page

    Private sp As New StackPanel
    Private MainGrid As New Grid

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Content = sp
        Dim b As New Button
        b.Content = "test"
        AddHandler b.Click, AddressOf test
        sp.Children.Add(b)
        sp.Children.Add(MainGrid)

        Application.Current.DebugSettings.EnableFrameRateCounter = False

    End Sub


    Private Sub test(sender As Object, e As RoutedEventArgs)

        MainGrid.Children.Clear()

        'this does NOT cause a leak
        'Dim testgr = New Grid
        'Dim canv As New CanvasControl
        'testgr.Children.Add(canv)
        'gr.Children.Add(testgr)


        'this DOES cause a leak
        MainGrid.Children.Add(New CanvasInGrid)

    End Sub

End Class



Public Class CanvasInGrid
    Inherits Grid

    Public button As Button
    Public Canvas As CanvasControl

    Public Sub New()
        Canvas = New CanvasControl
        'button = New Button 'if I do this with a button instead of the Canvas there is no leak

        Children.Add(Canvas)
        'Children.Add(button)
    End Sub


End Class

标签: uwpwin2d

解决方案


推荐阅读