I’m writing a sample windows phone 8 application. I’ve also installed the framework Async for .NET Framework 4, Silverlight 4 and 5, and Windows Phone.
But, await on a method doesn’t wait and my mainpage.xaml loads which tries to access a property which has not been filled as yet.
here is my code.
public static ObservableCollection<Model.CatalogCategory> Products { get; set; }
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
ApplicationViewModel vm = new ApplicationViewModel();
Products = await vm.LoadLocalDataAsync();
}
After this method, the mainpage.xaml is loaded which tries to access “Products” and throws a null reference exception.
is there a different approach that I need to take??
You didn’t understand the meaning of Async and ‘await’ correctly. ‘await’ awaits only for the rest of the code in that method block. The rest of the code after the await line is converted into a callback which is called only after the async task is completed. And this doesn’t block the entire method. The method is treated as completed and the control goes back to the caller.
You either remove the ‘await’ there or try to load the data in the MainPage_Loaded event or in OnNavigatedTo event. whatever suits you.