c# - UWP Windows 10 未触发 OnSuspending 事件

标签 c# windows-phone windows-store-apps win-universal-app uwp

我的 UWP 应用程序未触发 OnSuspending 事件,但此问题仅发生在运行 Windows 10 的 Windows Phone 上。当它作为 Windows 应用商店应用程序在我的本地计算机或模拟器上运行时,它按预期工作。

我正在使用此事件在应用程序关闭时保存我的应用程序设置,但这显然会导致 Windows Phone 出现重大问题,因为未触发此事件。

如您所见,应用启动时会初始化 OnSuspending 事件

public App()
{
    Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
        Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
        Microsoft.ApplicationInsights.WindowsCollectors.Session);
    this.InitializeComponent();
    this.Suspending += OnSuspending;
}

下面是应该调用但在 Windows Phone 10 中运行时不会调用的 OnSuspending 代码。

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();

    //TODO: Save application state and stop any background activity
    await Locator.MainPageViewModel.SaveSettings();

    deferral.Complete();
}

关于如何解决这个问题的任何想法或者是否有潜在的解决方法?

谢谢。

UPDATE-1:

当我通过按住标志键并单击叉号来终止我的应用程序时,关闭了应用程序,但它仍然不会触发 OnSuspending 事件,但 .net IDE 仍在运行。当我按 F5 再次运行该应用程序时,它会触发 OnSuspending 事件。我的应用程序启动但代码在 IDE 中停止运行。

最佳答案

来自官方App lifecycle documentation :

A note about debugging using Visual Studio: Visual Studio prevents Windows from suspending an app that is attached to the debugger. This is to allow the user to view the Visual Studio debug UI while the app is running. When you're debugging an app, you can send it a suspend event using Visual Studio. Make sure the Debug Location toolbar is being shown, then click the Suspend icon.

这意味着当您附加到 Visual Studio 调试器时,OnSuspending 事件不会被触发。如果要调试它,请通过选择相应的生命周期事件手动发送事件。

enter image description here

关于c# - UWP Windows 10 未触发 OnSuspending 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35233621/

相关文章:

data-binding - 根据 ViewModel 的属性在 View 中的 UserControl 之间切换

c# - 如何通过主机中的软件中止已建立的连接的消息找到 SocketException 的原因和原因?

c# - 我们可以从 C# 中的基类中的子类方法捕获异常吗?

windows-phone-7 - Windows 手机 MVVM : Button Command Can Execute and Command Paramtere

c# - WinRT : Show upper and lower AppBar independently

powershell - 在使用 Visual Studio 部署 Windows 10 UWP 应用程序期间出现错误 DEP0700 0x80073cf3

c# - 宿主在azure上开发wcf服务

c# - 从监听器队列中删除所有挂起的连接

xaml - 实现Windows Phone搜索界面

c# - 当 Windows Phone 应用程序处于 ARM 构建配置时,可移植类库不会重新编译