I'm writing Windows Phone 8.1 application and one of its part is LocalStorage access. I wrote code as presented below, but it has some serious issue. I need to initialize service using asynchronous methods and a while after, I'm using one of it's method (which is also asynchronous).
Service : IService
{
private XmlFormatter xmlFormatter;
public Service()
{
Initialize();
}
public async IList<Model> GetModelsAsync()
{
return xmlFormatter.GetModels();
}
private async void Initialize()
{
try
{
StorageFile item = (StorageFile)await ApplicationData.Current.LocalFolder.GetItemAsync(this.settings.Get<string>(SettingNames.DataFilename));
using (Stream readStream = await item.OpenStreamForReadAsync())
{
xmlFormatter = new XmlFormatter(XDocument.Load(readStream));
}
}
catch (FileNotFoundException)
{
CreateFile();
xmlFormatter = new XmlFormatter(null);
}
catch (Exception)
{
throw;
}
}
}
The problem is that GetModelsAsync methods runs before end of Initialize method, so xmlFormatter is null and I recieve NullReferenceException. How can I synchronize these methods?