简体   繁体   English

Windows Phone 8等待不等待

[英]Windows phone 8 await not waiting

I'm writing a sample windows phone 8 application. 我正在编写一个示例windows phone 8应用程序。 I've also installed the framework Async for .NET Framework 4, Silverlight 4 and 5, and Windows Phone . 我还安装了Async for .NET Framework 4,Silverlight 4和5以及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. 但是,等待一个方法不等待,我的mainpage.xaml加载试图访问尚未填充的属性。

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. 在此方法之后,加载mainpage.xaml,它尝试访问“Products”并抛出空引用异常。

is there a different approach that I need to take?? 我需要采取不同的方法吗?

You didn't understand the meaning of Async and 'await' correctly. 您没有理解Async的含义并正确地“等待”。 'await' awaits only for the rest of the code in that method block. 'await'仅等待该方法块中的其余代码。 The rest of the code after the await line is converted into a callback which is called only after the async task is completed. await行之后的其余代码将转换为仅在异步任务完成后调用的回调。 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. 您要么删除'await',要么尝试在MainPage_Loaded事件或OnNavigatedTo事件中加载数据。 whatever suits you. 什么适合你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM