仅在高使用率DataContractSerializer期间出现XmlException

时间:2012-06-28 15:24:51

标签: serialization windows-8 async-await

我有一个使用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;
    }
}

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

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

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

0 个答案:

没有答案