应用程序暂停在哪里保存状态

时间:2014-07-23 03:39:42

标签: c# windows-phone-8.1 savestate suspend

(注意:以下内容涉及适用于Windows Phone 8.1的Hub应用程序)

当Windows Phone挂起时,所有未保存的数据都将丢失。数据是否应在添加/更改时保存?或者它应该保存在Suspension上?或者是两者的混合?

具体做法是:

需要永久维护的重要数据,我认为保存它没有问题。但是,如果只需要几秒钟的数据,除非应用程序暂停,否则保存它似乎有点过分。

在一个方法中同时保存所有内容似乎更简洁,但这可能是我个人的偏好。

如果数据应该保存在暂停状态,那么它在以下方法中的位置是否重要? (这在OnSuspending()方法中调用。)

    public static async Task SaveAsync()
    {
        try
        {
            // Save the navigation state for all registered frames
            foreach (var weakFrameReference in _registeredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    SaveFrameNavigationState(frame);
                }
            }

            // Serialize the session state synchronously to avoid asynchronous access to shared
            // state
            MemoryStream sessionData = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, _sessionState);

            // Get an output stream for the SessionState file and write the state asynchronously
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
            using (Stream fileStream = await file.OpenStreamForWriteAsync())
            {
                sessionData.Seek(0, SeekOrigin.Begin);
                await sessionData.CopyToAsync(fileStream);
            }
        }
        catch (Exception e)
        {
            throw new SuspensionManagerException(e);
        }
    }

另外,一个附带问题,恢复数据应该只是在NavigationHelper_LoadState()方法中加载,对吗?

2 个答案:

答案 0 :(得分:2)

如何处理您的数据取决于几个因素:

  • 您的数据如何重要 - 如果您有一些重要数据,请立即保存,
  • 您的数据有多大 - 如果您的数据非常大,那么在应用暂停时可能无法保存数据 - 时间有限,
  • 想一想,如果你能够在恢复后重现数据 - 如果你有一些在应用程序中计算的数据,你可以在恢复后重现这个过程,那么可能就没有必要保存数据了。

如果很少的地方可以保存 - 设置(本地/漫游),LocalStorage(文件/数据库),还有缓存。

请注意,NavigationHelper包含一个帮助方法,可用于保存/恢复数据:

// in your Page
private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
    e.PageState.Add("yourKey", data);
}

它类似于 Dictionary ,它被序列化为文件 sessionStateFilename

您也可以手动对文件进行操作 - 它将非常相似。

答案 1 :(得分:0)

保存方法的位置是否重要?

  • 您只能信任'Window.Current.Activated'

    AddHandler Window.Current.Activated, AddressOf WindowActivated
    
    Private Sub WindowActivated(sender As Object, e As Windows.UI.Core.WindowActivatedEventArgs)
      If e.WindowActivationState = Windows.UI.Core.CoreWindowActivationState.Deactivated Then
        If TypeOf rootFrame.Content Is MyPage Then
            Dim MyPage1 = DirectCast(rootFrame.Content, MyPage)
            MyPage1.SaveAsync()
        End If
      End If
    End Sub
    

在一个方法中一次保存所有内容似乎更清晰。

  • 这也是我个人的偏好。

是否应在NavigationHelper_LoadState中恢复数据?

  • 我更喜欢App.OnLaunched
相关问题