使用WinRT时挂起事件未触发

36

我在使用WinRT时遇到了一个问题,无法在Windows Phone 8.1上挂起事件,它没有触发。我不知道为什么。这是我的代码:

/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
    InitializeComponent();

    Suspending += OnSuspending;
#if DEBUG
    this.displayRequest = new DisplayRequest();
#endif
}

/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">
/// The source of the suspend request.
/// </param>
/// <param name="e">
/// Details about the suspend request.
/// </param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    deferral.Complete();
}

我在var deferral = e.SuspendingOperation.GetDeferral();这一行设置了断点,并使用Visual Studio进行了调试。然后我按下手机上的启动按钮,运行了另一个应用程序并等待约10秒钟,但是OnSuspending没有运行。

有什么想法吗?

1个回答

65
在调试应用程序时,挂起事件将不会触发(但在正常运行应用程序时,它会在您从应用程序导航到其他屏幕后触发),如这篇博客所述:

 

......即使您的应用程序在屏幕之间来回切换,您也将永远等待它们触发!原因很简单:在调试应用程序时,Windows 不会将其挂起。

请注意,如果在挂起事件中出现某些问题(例如,在Frame.Navigate方法中传递一些复杂类并使用SuspensionManager),这可能会导致一些奇怪的应用程序行为。在调试模式下,您的应用程序将正常工作(没有挂起),但在没有调试模式的情况下会崩溃。

要测试您的应用程序如何表现,您需要手动触发 挂起,在Visual Studio中打开(或设置可见)调试位置工具栏,您将在那里找到一个生命周期事件下拉菜单,在那里选择Suspend,然后返回应用程序-Resume

enter image description here


请您提供任何证明链接吗? - CAMOBAP
3
@CAMOBAP 证明链接指的是什么? - Romasz
如果存在的话,为语句“您在调试时暂停事件不会触发”提供证明链接。 - CAMOBAP
7
@CAMOBAP我不确定为什么你想让我展示给你证明链接 - 它并不难找,所以在这里它是 - MSDN 博客 -> '如何调试过程生命周期事件',它说:如果您要通过在每个处理程序中设置断点并按F5启动Visual Studio中的调试器来调试先前部分中的代码,则会永远等待这些触发,即使您的应用程序在屏幕上来回切换!原因很简单:在调试应用程序时,Windows 不会将其挂起。 - Romasz
4
我找了好几个小时才找到这个珍贵的小提示。说实话,我并不知道我在寻找什么——我的症状(以及我在谷歌搜索的内容)是“Windows手机应用程序崩溃但不在调试模式下调试”,也许留下这个评论可以帮助谷歌将此答案链接给搜索同样问题的其他人。 这个答案不能解决问题,但它可以帮助您识别问题。 - Percy
@Rick 感谢您的评论,我已经稍微编辑了一下答案,希望能够帮助其他人节省一些时间。这似乎是一个相当普遍的问题,特别是与导航有关。 - Romasz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接