反序列化异步

时间:2013-06-20 16:33:56

标签: c# windows-8 microsoft-metro async-await

我收到的错误是说我的方法是在意外时间调用的。我当然不知道为什么。我每次尝试调用此方法时都会得到它。

public static async Task<List<Zajecia>> Deserialize()
{
  var files = ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName).GetResults();
  var file = files.FirstOrDefault(f => f.Name == "Plan_list.xml");

  if (file != null)
  {
    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("Plan_list.xml"))
    {
      XmlSerializer deserializer = new XmlSerializer(typeof(List<Zajecia>));
      return (List<Zajecia>)deserializer.Deserialize(stream);
    }
  }
  else
    return null;
}

我以这种方式称呼它

private async void Baton_Click(object sender, RoutedEventArgs e)
{
  _lista = await Deserialize();
}

这是对象_lista

public sealed partial class BasicPage1 : Plan.Common.LayoutAwarePage
{
  List<Zajecia> _lista = new List<Zajecia>();

  public BasicPage1()
  {
    this.InitializeComponent();
    this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
    ...
  }
}

调用堆栈:

mscorlib.dll!System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.WindowsRuntime.dll!System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore.AnonymousMethod__0(object o)
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(object state)
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
[Native to Managed Transition]

我正在寻找答案,但仍未找到任何答案。所以我在寻求帮助。

1 个答案:

答案 0 :(得分:4)

请勿致电GetResults。请改用await

public static async Task<List<Zajecia>> Deserialize()
{
  var files = await ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName);
  var file = files.FirstOrDefault(f => f.Name == "Plan_list.xml");

  if (file != null)
  {
    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("Plan_list.xml"))
    {
      XmlSerializer deserializer = new XmlSerializer(typeof(List<Zajecia>));
      return (List<Zajecia>)deserializer.Deserialize(stream);
    }
  }
  else
    return null;
}