【发布时间】:2017-05-29 13:43:04
【问题描述】:
我正在尝试从我之前编写的 web api 中获取列表。然后我将在 Xamarin.Forms ListView 中使用该列表。我的代码在这里:
public static class DataSource
{
public static async Task<Restoran[]> GetRestoransAsync()
{
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
var restorans = JsonConvert.DeserializeObject<Restoran[]>(result);
return restorans;
}
}
}
我的内容页面:
public class MenuPage : ContentPage
{
ListView listView;
List<Restoran> restorans = new List<Restoran>();
async Task LoadRestorans()
{
restorans = (await DataSource.GetRestoransAsync()).ToList();
}
public MenuPage(string masa)
{
var loadData = LoadRestorans();
loadData.Wait();
listView = new ListView(ListViewCachingStrategy.RecycleElement)
{
ItemsSource = restorans,
ItemTemplate = new DataTemplate(() => {
var nativeCell = new CustomCell();
return nativeCell;
})
};
}
}
但是当我调试这段代码时,“LoadRestorans()”方法在“restorans”列表初始化之前被调用。我想我不明白异步方法的心态。我该怎么办?
【问题讨论】:
标签: c# asynchronous xamarin async-await httpclient