snake_l 发表于 2015-5-21 12:35:49

win8 app基础知识(挂起、恢复状态的一些数据操作)

  在Win8 metro应用程序中,当程序挂起的时候,有一些数据需要临时保存起来,以便应用程序恢复到之前的状态
  下面这个SuspensionManager 类是微软写的demo,作下记录,下次会用到。
  


class SuspensionManager
{
    static private Dictionary sessionState_ = new Dictionary();
    static private List knownTypes_ = new List();
    private const string filename = "_sessionState.xml";
    // Provides access to the currect session state
    static public Dictionary SessionState
    {
      get { return sessionState_; }
    }
    // Allows custom types to be added to the list of types that can be serialized
    static public List KnownTypes
    {
      get { return knownTypes_; }
    }
    // Save the current session state
    static async public Task SaveAsync()
    {
      // Get the output stream for the SessionState file.
      StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
      IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);
      using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
      {
            // Serialize the Session State.
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary), knownTypes_);
            serializer.WriteObject(outStream.AsStreamForWrite(), sessionState_);
            await outStream.FlushAsync();
      }
    }
    // Restore the saved sesison state
    static async public Task RestoreAsync()
    {
      // Get the input stream for the SessionState file.
      try
      {
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
            if (file == null) return;
            IInputStream inStream = await file.OpenSequentialReadAsync();
            // Deserialize the Session State.
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary), knownTypes_);
            sessionState_ = (Dictionary)serializer.ReadObject(inStream.AsStreamForRead());
      }
      catch (Exception)
      {
            // Restoring state is best-effort.If it fails, the app will just come up with a new session.
      }
    }  
  
页: [1]
查看完整版本: win8 app基础知识(挂起、恢复状态的一些数据操作)