Bug 31207 - Global styles (including built-in ones) extend pages lifetime causing a memory leak
Summary: Global styles (including built-in ones) extend pages lifetime causing a memor...
Status: VERIFIED FIXED
Alias: None
Product: Forms
Classification: Xamarin
Component: Forms ()
Version: 1.4.3
Hardware: PC Windows
: Normal normal
Target Milestone: ---
Assignee: Stephane Delcroix
URL:
Depends on:
Blocks:
 
Reported: 2015-06-17 18:57 UTC by Sergey Komisarchik
Modified: 2015-07-20 06:58 UTC (History)
6 users (show)

Tags: AC docs
Is this bug a regression?: ---
Last known good build:


Attachments
Test case (567.26 KB, application/octet-stream)
2015-06-17 18:58 UTC, Sergey Komisarchik
Details


Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
VERIFIED FIXED

Description Sergey Komisarchik 2015-06-17 18:57:38 UTC
Global styles extend pages lifetime by holding strong references to them via AttachedCollection<T> objects of the Style class.

Test case:
1. Define global style in Application resources
2. Navigate to a page that has reference to the global style or Device.Styles.* style
3. Navigate back. Result: page is not garbage collected

Seems that the only valid workaround to this is to null out all Style properties of all VisualElements of the page after popping.


Complete example:

public class App : Application
{
    public App()
    {
        this.MainPage = new Page1();

        this.Resources = new ResourceDictionary();
        this.Resources["GlobalStyle"] = new Style(typeof(Label)) { Setters = { new Setter() { Property = Label.FontSizeProperty, Value = 100 } } };
    }
}

public class Page1 : ContentPage
{
    public Page1()
    {
        var stack = new StackLayout() { VerticalOptions = LayoutOptions.Center };

        stack.Children.Add(new Label() { VerticalOptions = LayoutOptions.Center, XAlign = TextAlignment.Center, Text = "Page 1" });
        stack.Children.Add(new Button() { Text = "try fix", Command = new Command(this.FixMemoryLeak) });

        this.Content = stack;
    }

    private WeakReference page2Tracker;

    protected override async void OnAppearing()
    {
        base.OnAppearing();

        if (this.page2Tracker == null)
        {
            var page2 = new Page2();

            this.page2Tracker = new WeakReference(page2, false);

            await Task.Delay(1000);
            await this.Navigation.PushModalAsync(page2);

            this.StartTrackPage2();
        }
    }

    private void FixMemoryLeak()
    {
        if (this.page2Tracker.IsAlive)
        {
            ((Label)((Page2)this.page2Tracker.Target).Content).Style = null;
        }
    }

    private async void StartTrackPage2()
    {
        while (true)
        {
            ((Label)((StackLayout)this.Content).Children[0]).Text = String.Format("Page1. But Page2 IsAlive = {0}", this.page2Tracker.IsAlive);
            await Task.Delay(1000);
            GC.Collect();
        }
    }
}

public class Page2 : ContentPage
{
    public Page2()
    {
        var label = new Label
                        {
                            VerticalOptions = LayoutOptions.Center,
                            HorizontalOptions = LayoutOptions.Center,
                            Text = "Page 2",
                            Style = (Style)Application.Current.Resources["GlobalStyle"],
                        };

        this.Content = label;
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
            
        await Task.Delay(1000);
        await this.Navigation.PopModalAsync();
    }
}
Comment 1 Sergey Komisarchik 2015-06-17 18:58:26 UTC
Created attachment 11654 [details]
Test case
Comment 2 Sergey Komisarchik 2015-06-17 19:12:00 UTC
Edit: Style holds strong references on attached VisualElements which in turn hold references on the Page
Comment 3 Kenneth Brodersen 2015-06-24 07:14:00 UTC
The following code will also result in a memory leak

_style = new Style(typeof(Button));
_style.Setters.Add(new Setter(){Property = Button.BackgroundColorProperty,    Value = Color.Blue});

_rootlayout.Children.Add(new Button()
                {
                    Text = "Just a test",
                    Style = _style
                });
Comment 4 Stephane Delcroix 2015-06-24 07:16:24 UTC
@Kenneth: the button won't be collected until the _style is collected. is that what you mean ? (just making sur it's the same issue)
Comment 5 Kenneth Brodersen 2015-06-24 07:48:53 UTC
@Stephan. I simply created a page with 20 buttons and set the style on each of these. Opening and closing the page about 180 times will result in an out of memory exception being thrown. So my guess is that it is the exact same issue. Should I create a new bug-report?
Comment 6 Stephane Delcroix 2015-06-24 08:24:16 UTC
@Kenneth: no, thank you. could you please attach your test case anyway so we're sure we hit the 2 birds with the same stone ?
Comment 7 Jason Smith [MSFT] 2015-06-26 02:32:43 UTC
Should be fixed in 1.4.4-pre1
Comment 8 Parmendra Kumar 2015-07-20 06:58:02 UTC
I have checked this issue with 1.4.4-pre2 and its working fine at my end.

Screencast with XF 1.4.3.6376: http://www.screencast.com/t/PmJMw5iNH0G

Screencast with XF 1.4.4-pre2 : http://www.screencast.com/t/EC4TOY8uFem

Hence closing this issue.