You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Debug模式下Xamarin应用App.xaml.cs意外重启问题咨询

问题描述

我在Xamarin Debug模式下使用应用连接设备,当系统显示“Connecting to device...”正在连接设备时,按下返回键回到桌面后再返回应用,发现App.xaml.cs代码会重新执行,页面先显示Example_A_Page,随后跳转至Example_B_Page。但在非Debug模式下重复该操作,应用停留在Example_B_Page。

相关截图:
连接设备界面:
连接设备界面
应用页面界面:
应用页面界面

伪代码展示
public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        MainPage = new NavigationPage(new Example_A_Page());
    }
}

public partial class Example_A_Page : ContentPage
{
    public Example_A_Page()
    {
        InitializeComponent();
    }

    protected async override void OnAppearing()
    {
        await Navigation.PushPopupAsync(new Example_B_Page());
    }
}

public partial class Example_B_Page : ContentPage
{
    public Example_B_Page()
    {
        InitializeComponent();
    }

    private async void Button_Clicked(object sender, EventArgs e)
    {
        //Do the connection behavior...
        //Connected to the device...
    }
}
原因分析
  • Debug模式下进程易被回收:Debug模式下Xamarin应用会附加调试器,系统对处于调试状态的后台进程回收优先级更高。连接设备操作会占用较多资源,此时退回桌面,系统大概率会回收应用进程;再次打开时进程重启,App构造函数重新执行,初始化MainPage为Example_A_Page,触发其OnAppearing方法跳转至Example_B_Page。
  • Release模式下后台保活更稳定:Release模式无调试器附加,同时编译阶段会做内存优化、移除调试钩子,系统对这类应用的后台进程管理更宽松,退到桌面后进程不易被回收,再次回到前台时直接恢复原有页面状态,因此停留在Example_B_Page。
  • 导航栈状态的差异:Debug模式下进程重启会清空原有导航栈,重新构建页面层级;而Release模式下进程存活,导航栈状态被完整保留,即使Example_A_Page的OnAppearing触发,也不会重复执行跳转逻辑。

内容的提问来源于stack exchange,提问作者Hannah.C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 10:35:19