Xamarin.Forms styles causing WeakReference leak

I spent a lot of time looking for memory leaks in our Xamarin.Forms Android app. After many dead ends and false dawns, I think I may have come across what causes the problem.

Using the Xamarin Profiler, I see that as soon as I create a style and apply it to the control (or, in fact, just an implicit style), we get the remaining “Live” multiple WeakReferences, ie do not collect garbage.

Note that I assume that the objects to which they refer were GC'd (because the reference to the object is weak), but WeakReferences themselves remain.

Now, of course, WeakReferences are small, I know - but when you have hundreds of push / pop pages created at each iteration, then the memory adds up and we have a significant leak.

Here are the details. Using Xamarin.Forms 2.3.4.270 (we are not updating because we want to keep known problems!) Working on Android is a physical device.

App.xaml:

<?xml version="1.0" encoding="utf-8"?>
<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:ProfiledFormsApp2;assembly=ProfiledFormsApp2" 
     x:Class="ProfiledFormsApp2.App">
    <Application.Resources>
        <ResourceDictionary>
            <Style TargetType="Label">
                <Setter Property="FontSize" Value="Large" />
                <Setter Property="TextColor" Value="Blue" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

XAML page:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage Title="Plain Page" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="ProfiledFormsApp2.PlainPage">
    <ContentPage.Content>
        <StackLayout>
            <StackLayout Orientation="Horizontal">
                <Label Text="Core Navigation"/>
                <Label Text="Number of items:" />
                <Label Text="{Binding ItemsCount}" />
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

When I go to the previous page and return 3 times, we will create the following WeakReference classes (and related ones) - a screenshot below from the Profiler snapshot.

Please note that we have 55 WeakReferences. Drilling into these shows:

Interestingly, these WeakReferences seem to be created as part of the Ghost and Trigger. Looking at the call tree for the top, you get:

, , WeakReference BindableObject .

, WeakReference - - Behavior?

Profiler, , , GC'd. , - Theme/Behavior/Trigger.

Xamarin.Forms GitHub - , , .

- ?

+4
1

, , .

:

<Button x:Name="btnSave" Style="{StaticResource SaveButtonStyle}" Content="Save"/>

protected override void OnDisappearing()
{
    btnSave.Style = null;

    base.OnDisappearing();
}

Triggers Behaviors ( ).

, - . , .

+1

Source: https://habr.com/ru/post/1691694/


All Articles