Suspending event not raising using WinRT

2018-12-31 15:41发布

问题:

I\'m having a problem with suspending event on Windows Phone 8.1 using WinRT, it does not fire. I don\'t know why. This is my code:

/// <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();
}

I set a breakpoint on the line var deferral = e.SuspendingOperation.GetDeferral(); and debugged it with Visual Studio. Then I pressed the start button on my phone and ran another app and waited about 10 seconds. OnSuspending is not running.

Any ideas?

回答1:

Suspending event won\'t fire while you are debugging (but while running your App normal, it will fire just after you navigate away from the App) as it is said also at this blog:

...you will wait forever for these to trigger, even though your app switches back and forth to the screen! The reason is simple: while an app is being debugged, Windows will not suspend it.

Note that this may lead to some weird app behavior, when there is something wrong in Suspending event - for example if you pass some complex class in Frame.Navigate method and you use SuspensionManager. While debugging your app will work just fine (no suspension), but will crash without debug mode.

To test how your App behaves, you will have to invoke the Suspending manuallt, open (or set visible) Debug location toolbar in Visual Studio, there you will find a dropdown Lifecyce events, choose there Suspend, and then to return the App - Resume.

\"enter