Making sync code depend on async code



In my current project I am storing the state of certain objects in XML files. As i am working in a WPF project i am required to do this using async methods.


Because of that i am encountering a problem when loading up my application. I was to recreate the state of these objects from the XML files, which would have to be done async, but my content depends on the state of these objects, which in my case results in that the objects haven't been fully instantiated before i work with them.


In short: My sync methods depends on my async methods having instantiated my objects when launching my application.


Below is a bit of code that shows how i am reading an entire folder's xml files and generating a List of objects.



public List<Restaurant> restaurant = new List<Restaurant>();

public async void ReadRestaurantAsync()
{
IStorageFolder filesFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("folder");
var storageFiles = await filesFolder.GetFilesAsync();

foreach (var storageFile in storageFiles)
{
using (IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read))
using (Stream inputStream = stream.AsStreamForRead())
{
DataContractSerializer serializer = new DataContractSerializer(typeof (Restaurant));
Restaurant objectRead = serializer.ReadObject(inputStream) as Restaurant;
restaurant.Add(objectRead);
}
}
}


Now when i call this async method from my MainPage, i can't work with the object Restaurant, as it hasn't been fully instantiated.


I guessing i will have to wait on the method being fully executed before trying to interact with Restaurant, but that seems a bit odd as well, as it ruins the whole idea about async methods.


No comments:

Post a Comment