我在使用Xamarin处理内存泄漏时遇到很多困难。我特别在挣扎着一套。为了说明这种泄漏,我创建了最简单的程序,该程序可以在两个页面之间进行切换。代码如下:
App.xaml.cs:
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Diagnostics;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace MemoryLeak
{
public partial class App : Application
{
public static App m_app;
MainPage[] pages = new MainPage[2];
public void SetPage(int idx)
{
MainPage page = pages[idx % 2];
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Debug.WriteLine(string.Format("{1}:mem={0}", System.GC.GetTotalMemory(true), idx));
page.ShowMemoryUse();
MainPage = page;
}
public App()
{
InitializeComponent();
m_app = this;
pages[0] = new MainPage(0);
pages[1] = new MainPage(1);
SetPage(0);
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
MainPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MemoryLeak"
x:Class="MemoryLeak.MainPage">
<StackLayout>
<!-- Place new controls here -->
<Label x:Name="myText" Text="Welcome to Xamarin.Forms!"
HorizontalOptions="Start"
VerticalOptions="Center"/>
<Button Text="Next" Clicked="OnButtonClicked" />
</StackLayout>
</ContentPage>
MainPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Diagnostics;
namespace MemoryLeak
{
public partial class MainPage : ContentPage
{
int m_id;
public MainPage(int id)
{
InitializeComponent();
m_id = id;
}
public void ShowMemoryUse()
{
myText.Text = string.Format("{1}: {0}", System.GC.GetTotalMemory(true), m_id);
}
void OnButtonClicked(object sender, EventArgs args)
{
App.m_app.SetPage(m_id == 0 ? 1 : 0);
}
}
}
现在,如果我在UWP下运行该程序并反复单击“下一步”按钮,则会看到内存使用量无限制地增加。如果使用Performance Profiler,我还会看到许多从未释放的对象。例如,单击“下一步”按钮40次会产生以下搁浅的对象:
还有更多
我看不到我在做什么错。 Xamarin是否有问题?我是否不应该通过辅助“ MainPage”来交换页面?
谢谢。