使用WPF ListBox和DataTable的内存泄漏

时间:2016-02-26 14:41:32

标签: wpf vb.net xaml memory-leaks

我似乎遇到了导致内存泄漏的情况。当我运行此代码并在单击“Do It”按钮时观察实时诊断时,似乎我的数据表永远不会被释放。我不明白什么可能根植这些数据。任何人都可以向我提供有关原因的见解吗?那可以做些什么呢?

MainWindow.Xaml

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Button Content="Do It" Margin="5 5 5 0" Click="Button_Click" DockPanel.Dock="Top" />
        <ListBox Margin="5" Name="lister">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding LastName}" />
                        <TextBlock Text=", " />
                        <TextBlock Text="{Binding FirstName}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </DockPanel>
</Window>

MainWindow.Xaml.vb

Imports System.Data

Class MainWindow
    Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim tbl As New DataTable
        tbl.TableName = "Contacts"
        tbl.Columns.Add("LastName")
        tbl.Columns.Add("FirstName")
        For idx As Integer = 1 To 50000
            Dim row As DataRow = tbl.NewRow()
            row.Item("LastName") = $"Last {idx}"
            row.Item("FirstName") = $"First {idx}"
            tbl.Rows.Add(row)
        Next
        lister.ItemsSource = tbl.AsDataView()
    End Sub
End Class

0 个答案:

没有答案