我是异步和等待编程风格的新手。如何解决以下问题:
我先调用下面的代码。这里的问题是第一行正在等待需要填充的categoriesvm.Categorieslist
,它不需要,但是第二行被调用。(我认为这是等待的默认行为)
如何确保仅在categoriesvm.Categorieslist
第一行中填充第二行时才调用第二行?
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
categoriesvm.GetCategories();
BookCategories.DataContext = from vm in categoriesvm.Categorieslist select vm;
}
在上面的代码中,当我执行第一行时,它会低于Categorieslist
我在上面访问的列表。
public async void GetCategories()
{
Categorieslist = new ObservableCollection<Categories>(await PhoneClient.GetDefaultCategories());
}
下面phoneclient
是
public class PhoneClient
{
private static readonly HttpClient client;
public static Uri ServerBaseUri
{
get { return new Uri("http://169.254.80.80:30134/api/"); }
}
static PhoneClient()
{
client =new HttpClient();
client.MaxResponseContentBufferSize = 256000;
client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
}
public async static Task<List<Categories>> GetDefaultCategories()
{
HttpResponseMessage getresponse = await client.GetAsync(ServerBaseUri + "Categoryss");
string json = await getresponse.Content.ReadAsStringAsync();
json = json.Replace("<br>", Environment.NewLine);
var categories = JsonConvert.DeserializeObject<List<Categories>>(json);
return categories.ToList();
}
}