代码改变世界

【原】关于Silverlight IsolatedStorage的小陷阱

2009-09-23 17:42  拖鞋不脱  阅读(2053)  评论(0编辑  收藏  举报

Silverlight中的IsolatedStorage是一种类似Cookied的静态存储机制。可以将一些基本类型(String,Int)的信息甚至是自定义类型的序列化后静态存储于客户端本地文件中。怎样应用IsolatedStorage进行存储或读取,已有较多文章讨论。比如“详解Silverlight 2中的独立存储(Isolated Storage)”。这里只记录一些操作中需要注意的地方:

保存独立存储需要调用Save方法

主要是在操作IsolatedStorageSettings对象的情况下,当向其中添加某个配置项时,比如:

IsolatedStorageSettings appSetting = IsolatedStorageSettings.ApplicationSettings;
appSetting["App"] = IsolateData.GetIsolateData(AppContent.Text);

此时只是把信息存放在内存中,并没有实际放入文件中,需要调用IsolatedStorageSettings对象的Save方法,才能实现静态存储。

 

扩大存储空间,需要在用户启动的方法中调用

所谓用户启动,就是类似Button的Click事件的处理函数。在这里调用扩大存储空间的方法:

IsolatedStorageFile.GetUserStoreForApplication().IncreaseQuotaTo(10 * 1024 * 1024);

这样,会弹出让用户确认扩大存储空间的提示。如果放在其他非用户启动的方法中,比如程序初始化中,则不会弹出提示,上述方法也会返回false.

 

如果要把某用户自定义类型的对象存放于静态存储中,需要有公开的无参构造函数,或者用特性标记。

如果尝试存储一个没有无参构造函数的对象,则在调用Save方法时,会抛出如下异常:

image

如果添加一个无参的构造函数,则不会抛出异常。

但这里要注意的是,如果你的对象拥有非公开的无参构造函数,比如用于单例模式的对象。那么也是不会抛出异常的,但却会有意想不到的后果——所有存储在IsolatedStorage里的信息全部被清空。

所以,比较保险的做法是,要么提供一个公开的无参构造函数,并将所有需要保存的属性或字段设为公开。或者用DataMemeber特性来标记那些需要保存的成员。

此外,还需要用户自定义的类型是公共类型(public),或使用InternalsVisibleToAttribute 属性以便对内部成员启用序列化

 

所有在操作IsolatedStorage中抛出的异常都是IsolatedStorageException类型的

这点比较无奈,也就是说你无法通过抛出异常的类型来判断到底是存储空间不足,还是独立存储被禁用,还是由于多个App同时操作同一独立存储导致的异常,而偏偏针对上面不同情况,需要作出不同的处理。那么要么通过Message判断,要么给出统一的模糊的异常提示,总之没有找到比较好的解决办法。

————————————————————————————————————————————————

最后附送MSDN上的关于IsolatedStorage的七个Best Practice:

  • Wrap all calls to isolated storage within try/catch blocks to be resilient to potential IsolatedStorageExceptions, which can be thrown if isolated storage is disabled or if the store has been deleted.

把所有对Isolated Storage的调用都包裹在Try/Catch块中来捕获潜在的IsolatedStorageExceptions。因为导致异常的因素实在很多(禁用独立存储、独立存储空间不足、多个应用程序同时操作一份独立存储导致的不一致性,还有在某些情况下操作独立存储,可能会提示独立存储不可用)。

  • If your Silverlight application needs to store a lot of data in isolated storage, consider hosting it on its own site so that it won't affect other applications on the site and other applications won't affect it.

如果你的Silverlight应用程序需要独立存储很多的数据,最好把它放在一个单独的网站,这样就不会影响到其他的应用程序。因为所有放在同一网站下的Silverlight应用程序,使用的是同一定额,它们会互相挤占。

  • If you have a group of Silverlight applications that need to share data on the client, host them on the same site.

如果几个Silverlight应用程序需要在客户共享数据,把它们放在同一网站下。

  • Keep isolated storage paths as small as possible to prevent the internal full path from reaching the 260-character limit.

让独立存储的路径越小越好,避免路径长度达到260个字符的限制。

  • Encrypt sensitive data stored in isolated storage.

加密保存在Isolated Storage里的敏感数据,因为它们实际是文本文件,直接可读的。

  • Use IsolatedStorageSettings to store objects and simple settings in isolated storage.

使用IsolatedStorageSettings来储存对象和简单的设置。

  • Use IsolatedStorageFile if you want to use file and stream-based APIs, are storing large amounts of data, or need fine-grained control over the contents of isolated storage.

如果需要使用文件或者基于流的API,保存大数据,或者需要细粒度的控制独立存储中的内容,则使用IsolatedStorageFile。