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没有运行。

有任何想法吗?

4

1 回答 1

65

暂停事件在您调试时不会触发(但在正常运行您的应用程序时,它将在您离开应用程序后立即触发),正如在此博客中所说的那样:

...您将永远等待这些触发,即使您的应用程序来回切换到屏幕!原因很简单:在调试应用程序时,Windows 不会暂停它。

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

要测试您的应用程序的行为方式,您必须调用暂停手册,在 Visual Studio中打开(或设置可见)调试位置工具栏,在那里您会找到一个下拉生命周期事件,选择那里Suspend,然后返回应用程序 - Resume

在此处输入图像描述

于 2014-06-08T06:51:54.487 回答