MajQel
MajQel

Reputation: 155

Deserializing async

I get error that says my method is called in unexpected time. I don't have any idea why of course. I get it every time I try to call this method.

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;
}

And I'm calling it in this way

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

Here is object _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;
    ...
  }
}

Call stack:

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]

I am searching for answers but still haven't found anything. So I'm asking for help.

Upvotes: 0

Views: 3500

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457137

Do not call GetResults. Use await instead:

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;
}

Upvotes: 4

Related Questions