.NET MAUI(Xamarin Forms)页面/自定义视图何时被销毁



我是Xamarin/.NET MAUI应用程序开发的新手。我开始为Android设备开发一个示例.NET MAUI应用程序
我正在努力了解如何/何时销毁(处置(页面和我的自定义视图。我读了一些网页,但我真的不明白在.NET MAUI(或Xamarin(中是如何工作的。

我有三页:MainPageSecondPageTestMapPage
SecondPage有一个可导航到TestMapPage的按钮。它实例化一个TestMapPage对象并将其传递给Navigation.PushAsync()
TestMapPage包含一个自定义视图TestMapView,它由我的自定义视图渲染器TestMapViewRenderer渲染。我在渲染器中创建了一个MapView对象(来自Naxam.Mapbox.Droid(,并在TestMapPage中显示地图。地图显示在模拟器上,工作正常。

当我导航回MainPage时,我认为SecondPageTestMapPageTestMapView(以及TestMapViewRenderer中的所有对象(将被销毁。但是,当我在渲染器中的Dispose()上设置一个断点,并在中导航回SecondPageMainPage时,它永远不会被击中。

我的问题:

  1. 当我返回到MainPage时,视图和视图渲染器中的SecondPageTestMapPageTestMapView和所有其他对象(如MapboxMap(是否保留在某个位置
  2. 页面和视图何时销毁/处置
  3. 如果这些页面对象一直保存在某个地方,直到应用程序关闭,这是正常行为吗
  4. 如果行为不正常,我该如何解决

我担心内存泄漏。。。

MainPage.xaml.cs

public partial class MainPage : ContentPage
{
// ...
private async void OnGoToSecondPageClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new SecondPage());
}
}

SecondPage.xaml.cs

public partial class SecondPage : ContentPage
{
// ...
private async void OnMapShowClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new TestMapPage());
}
}

TestMapPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MapTest"
x:Class="MapTest.TestMapPage">
<StackLayout Margin="5">
<local:TestMapView
x:Name="map"
VerticalOptions="FillAndExpand" 
HorizontalOptions="CenterAndExpand"/>
</StackLayout>
</ContentPage>

TestMapView.cs

public class TestMapView : View { }

TestMapViewRenderer.cs

public partial class TestMapViewRenderer : ViewRenderer<TestMapView, Android.Views.View>
{
private MapboxMap map;
public TestMapViewRenderer(Context context) : base(context) {}
protected override void OnElementChanged(ElementChangedEventArgs<TestMapView> e)
{
base.OnElementChanged(e);
// ...
if (Control == null)
{
var mapView = new MapView(Context);
SetNativeControl(mapView);
mapView.GetMapAsync(this);
}
}
public void OnMapReady(MapboxMap map)
{
this.map = map;
this.map.SetStyle(Resources.GetString(Resource.String.mapbox_style_satellite), this);
}
protected override void Dispose(bool disposing)
{
// A breakpoint never hits on this line. Why?
base.Dispose(disposing);
}
// ...
}

据我所知;

  1. 不,在每次导航中都会创建新的页面实例,因此,页面是由.NET本身创建并保存在内存中的,一旦垃圾回收达到某个阈值,内存就会空闲。在那之前,这些页面都在内存中,但不打算在将来使用
  2. 当GC决定时,Xamarin/MAUI并不关心视图
  3. 不幸的是,是的
  4. 这很正常,你可以通过使用@ToolmakerSteve所指的来克服

最新更新