设为首页 收藏本站
查看: 1066|回复: 0

Windows 8 系列(三):挂起管理(Suspension Management )

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-5-22 13:32:21 | 显示全部楼层 |阅读模式
  从我发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 sessionState_ = new Dictionary();
18         private const string filename = "_sessionState.xml";
19         static private List knownTypes_ = new List();
20
21         static public Dictionary SessionState
22         {
23             get { return sessionState_; }
24         }
25
26         static public List 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), 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), knownTypes_);
71             sessionState_ = (Dictionary)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
{
    ///
    /// Provides application-specific behavior to supplement the default Application class.
    ///
    sealed partial class App : Application
    {
        public Frame CurrentFrame { get; set; }
        ///
        /// 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().
        ///
       public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
        ///
        /// 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.
        ///
        /// Details about the launch request and process.
        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),);
        }
        
        ///
        /// 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.
        ///
        /// The source of the suspend request.
        /// Details about the suspend request.
        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 这两个关键词。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-69611-1-1.html 上篇帖子: Windows 8实用窍门系列:12.windows 8的文件管理---1.File创建和String Stream Buffer方式读写 下篇帖子: [Windows Phone 8开发系统]1. 环境搭建与创建第一个项目!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表