summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Issue1703.cs
blob: fac9a3dd9f95d53c78189ab308e9e4830a07083a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;

using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms.Controls
{
	[Preserve (AllMembers=true)]
	[Issue (IssueTracker.Github, 1703, "Memory leak when navigating a page off of a navigation stack", PlatformAffected.Android | PlatformAffected.iOS | PlatformAffected.WinPhone)]
	public class Issue1703 : NavigationPage
	{
		static List<WeakReference> s_pageRefs = new List<WeakReference>();

		public Issue1703 ()
		{
			Navigation.PushAsync (GetMainPage ());
		}

		public static Page GetMainPage()
		{
			return CreateWeakReferencedPage();
		}

		static Page CreateWeakReferencedPage()
		{
			GC.Collect();
			var result = CreatePage();
			s_pageRefs.Add(new WeakReference(result));

			// Add a second unreferenced page to prove that the problem only exists
			// when pages are actually navigated to/from
			s_pageRefs.Add(new WeakReference(CreatePage()));
			GC.Collect();
			return result;
		}

		static Page CreatePage()
		{
			var page = new ContentPage();
			var contents = new StackLayout();

			contents.Children.Add(
				new Button
				{
					Text = "Next Page",
					Command = new Command(() => page.Navigation.PushAsync(CreateWeakReferencedPage()))
				});
			contents.Children.Add(
				new Label
				{
					Text = string.Format(
						"References alive at time of creation: {0}",
						s_pageRefs.Count(p => p.IsAlive)),
					HorizontalOptions = LayoutOptions.CenterAndExpand
				});

			page.Content = contents;
			return page;
		}
	}
}