mercredi 6 mai 2015

WPF ContextMenu + MenuItem memory leak

Can anybody help with WPF and how-to free ContextMenu + MenuItem. As I’m using it, it keeps hold a WeakReference.

I have created a demo application, where it adds 10000 UserControl to a StackPanel and then removes it again. If the UserControl ContextMenu has no MenuItem, everything is fine. But if it contains a

<UserControl.ContextMenu>
    <ContextMenu>
        <MenuItem Name="Properties" />
    </ContextMenu>
</UserControl.ContextMenu>

Then Teleriks profiler reports 180.050 instances of WeakReference. How can I free this up?

I have googled without luck - I have read the following pages, but couldn't see any solution, else I have missed some of the informations.

Strange wpf memory leak

WPF Combobox "leaks" memory

http://ift.tt/1DRVfIZ

Demo application:

MainWindow.xaml has added:
<StackPanel>
    <StackPanel Orientation="Horizontal">
        <Button Content="Add Empties" Click="AddClick" Margin="3" />
        <Button Content="Add With ContextMenu" Click="AddWithContextMenuClick" Margin="3" />
        <Button Content="Remove" Click="RemoveClick"  Margin="3" />
    </StackPanel>
    <StackPanel x:Name="PagesStackPanel">
    </StackPanel>
</StackPanel> 

MainWindow.xaml.cs has added:
private void AddClick(object sender, RoutedEventArgs e)
{
    for (var i = 0; i < 10000; i++)
    {
        PagesStackPanel.Children.Add(new ChildViewEmpty());
    }
}

private void RemoveClick(object sender, RoutedEventArgs e)
{
    PagesStackPanel.Children.Clear();
}

private void AddWithContextMenuClick(object sender, RoutedEventArgs e)
{
    for (var i = 0; i < 10000; i++)
    {
        PagesStackPanel.Children.Add(new ChildViewWithMenu());
    }
}

ChildViewEmpty.xaml has added: 
<Grid />

ChildViewWithMenu.xaml has added:
<UserControl.ContextMenu>
    <ContextMenu>
        <MenuItem Name="Properties" />
    </ContextMenu>
</UserControl.ContextMenu>

I’m running this on Windows 8.1 with .NET 4.5

Aucun commentaire:

Enregistrer un commentaire