从我发Windows 8系列第一篇文章:Windows 8 系列(一):win 8 简介 到现在有一个月了,原本计划等Windows 8 beta(Windows 8 Consumer Preview)出来以后看看有什么变化,然后再来基于Windows 8 Beta 来写相关的技术博文,而不是基于Windows 8 Developer Preview,毕竟 DP(Developer Preview) 版本还有很多功能和api会在beta版本中有所修改,而且我不知道到底有多少改动。
从现在看来,确实有部分改动,包括应用程序的生命周期都有了变化(详见Windows 8 系列(二):Metro Style 应用程序生命周期(Metro Style Application Life Cycle))。我在此想介绍的是挂起管理,顾名思义是应用在触发挂起事件时我们需要做的一件事:保存数据。其实这个跟windows phone 中的墓碑机制有点像,只不过墓碑是15秒限制,而win 8的挂起限制是5秒。
在DP版本中,用vs 创建系统自带的Metro style app模板程序后,你会发现工程中有个名为SuspensionManager.cs的文件,而在Beta版本中却没有了这个文件,我觉得可能微软不想把开发者的思维限制住(比如用户是不是真的需要一个字典来存储数据),但是,我觉得对于新手来说,这个类可以方便的进行临时数据保存的管理。代码如下:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using Windows.Storage;
7 using Windows.Storage.Streams;
8 using System.Runtime.Serialization;
9 using System.IO;
10 using Windows.ApplicationModel;
11
12
13 namespace WeiboForWindows8Beta
14 {
15 static class SuspensionManager
16 {
17 static private Dictionary<string, object> sessionState_ = new Dictionary<string,object>();
18 private const string filename = "_sessionState.xml";
19 static private List<Type> knownTypes_ = new List<Type>();
20
21 static public Dictionary<string, object> SessionState
22 {
23 get { return sessionState_; }
24 }
25
26 static public List<Type> KnownTypes
27 {
28 get { return knownTypes_; }
29 }
30
31 // @todo: Worker to workaround issues with Developer Preview.
32 static async public Task SaveAsync()
33 {
34 await Windows.System.Threading.ThreadPool.RunAsync((wiArgs) =>
35 {
36 SuspensionManager.SaveImplAsync().Wait();
37 }, Windows.System.Threading.WorkItemPriority.Normal);
38 }
39
40 static async private Task SaveImplAsync()
41 {
42 // Get the output stream for the SessionState file
43 StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
44 IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);
45 IOutputStream outStream = raStream.GetOutputStreamAt(0);
46
47 // Serialize the Session State
48 DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
49 serializer.WriteObject(outStream.AsStreamForWrite(), sessionState_);
50 await outStream.FlushAsync();
51 }
52
53 // @todo: Worker to workaround issues with Developer Preview.
54 static async public Task RestoreAsync()
55 {
56 await Windows.System.Threading.ThreadPool.RunAsync((wiArgs) =>
57 {
58 SuspensionManager.RestoreImplAsync().Wait();
59 }, Windows.System.Threading.WorkItemPriority.Normal);
60 }
61
62 static async private Task RestoreImplAsync()
63 {
64 // Get the input stream for the SessionState file
65 StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
66 if (file == null) return;
67 IInputStream inStream = await file.OpenReadAsync();
68
69 // Deserialize the Session State
70 DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
71 sessionState_ = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
72 }
73
74 //获取Key对应的值
75 static public object GetValueByKey(string key)
76 {
77 if (sessionState_.ContainsKey(key))
78 return sessionState_[key];
79 else
80 return null;
81 }
82 //添加或者设置相应的值
83 static public void SetValueByKey(string key, object value)
84 {
85 if (sessionState_.ContainsKey(key))
86 sessionState_[key] = value;
87 else
88 sessionState_.Add(key, value);
89 }
90 //清除某个Key和对应的值
91 static public void RemoveKey(string key)
92 {
93 if (sessionState_.ContainsKey(key))
94 sessionState_.Remove(key);
95 }
96 }
97 }
以上代码中最后三个函数是我自己加上的,这简化了用户对字典数据的操作。
在App.xaml.cs文件中,有相关代码的调用:
using System;
using System.Text;
using WeiboForWindows8Beta.Utils;
using WeiboService;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
namespace WeiboForWindows8Beta
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
public Frame CurrentFrame { get; set; }
/// <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()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
SuspensionManager.RestoreAsync
}
// Create a Frame to act navigation context and navigate to the first page
if (CurrentFrame==null)
CurrentFrame = new Frame();
CurrentFrame.Navigate(typeof(WeiboForWindows8Beta.View.Login),);
}
/// <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>
void OnSuspending(object sender, SuspendingEventArgs e)
{
//TODO: Save application state and stop any background activity
SuspensionManager.SaveAsync()
}
}
}
在构造函数中给Suspending事件添加了OnSuspending函数,应用程序会在挂起事件发生时,触发OnSuspending。
SuspensionManager.SaveAsync()会把我们之前保存到SessionState中的数据保存至_sessionState.xml文件中,而SaveAsync则是从_sessionState.xml文件中读取出来。
获取之前用C#的童鞋感觉对async 这个关键词和用法比较模糊,我会在专门的一篇文章来介绍await 和 async 这两个关键词。