0

我有一个使用 DataContractSerializer 的有效 Windows 8 缓存解决方案,它仅在“快速”使用 UI 时引发 XmlException“文件意外结束”。

public static class CachingData<T>
{
    public static async void Save(T data, string filename, StorageFolder folder = null)
    {
        folder = folder ?? ApplicationData.Current.LocalFolder;
        try
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    serializer.WriteObject(outStream.AsStreamForWrite(), data);
                    await outStream.FlushAsync();
                }
            }
        }
        catch (Exception exc)
        {
            throw exc;
        }
    }

    public static async System.Threading.Tasks.Task<T> Load(string filename, StorageFolder folder = null)
    {
        folder = folder ?? ApplicationData.Current.LocalFolder;
        T data = default(T);
        StorageFile file = await folder.GetFileAsync(filename);
        using (IInputStream inStream = await file.OpenSequentialReadAsync())
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            data = (T)serializer.ReadObject(inStream.AsStreamForRead());
        }
        return data;
    }
}

例如,用户单击列表 CachingData.Load 中的项目,通过 await 调用异步,检查 FileNotEoundException 并从磁盘或网络加载数据,完成时序列化。首次加载后,用户选择列表中的另一个项目并循环重复。

当“首次加载后”变为“不等待加载”并且所选项目不可用缓存时,就会出现此问题。

不太确定如何继续,甚至如何调试,希望只是忽略将允许应用程序继续(只是没有很好的缓存速度增加)

4

0 回答 0