我有一个异步空隙,我在其中获取需要与本地数据进行比较的数据,然后填充listView。
CheckReservations(currentDate); //async void
BindingContext = viewModel = new ItemsViewModel(); //the model
但是很明显,模型要比异步void更快地执行,有什么方法可以等待void完成然后填充模型吗?在获得HTTP响应之前,我已经使用了await
关键字,但这没有帮助,到目前为止,文档对我来说还不是很好。
我将代码更改为以下内容:
protected async Task<ArrayList> CheckReservations(string day)
{
if (CrossConnectivity.Current.IsConnected)
{
try
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("reservation_day", day));
var content = new FormUrlEncodedContent(postData);
var response = await _client.PostAsync(Url, content);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
List<Reservations> myData = JsonConvert.DeserializeObject<List<Reservations>>(json);
foreach(Reservations res in myData)
{
reservations.Add(res.reservation_time);
}
return reservations;
}
else { return null; }
}
catch (Exception e)
{
Debug.WriteLine("" + e);
}
}
return reservations ;
}
并致电:
reservations = (ArrayList) CheckReservations(currentDate);
但是我得到了错误:
Cannot convert type System.Threading.Tasks.Task<System.Collections.ArrayList> to System.Collections.ArrayList.
那我在做什么错了?
答案 0 :(得分:3)
我有一个异步空隙,我在其中获取需要与本地数据进行比较的数据,然后填充listView。
如果您自己使此异步无效,建议您改为使用Task进行更改,除非是生命周期方法,否则异步无效是一种不好的做法。
await CheckReservations(currentDate); //async Task
this.BindingContext = viewModel = new ItemsViewModel(); //the model
请确保您的CheckReservations方法是一项任务,
protected async Task<ArrayList> CheckReservations(string day)
{
if (CrossConnectivity.Current.IsConnected)
{
try
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("reservation_day", day));
var content = new FormUrlEncodedContent(postData);
var response = await _client.PostAsync(Url, content);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
List<Reservations> myData = JsonConvert.DeserializeObject<List<Reservations>>(json);
foreach(Reservations res in myData)
{
reservations.Add(res.reservation_time);
}
return reservations;
}
else { return new ArrayList(); }
}
catch (Exception e)
{
Debug.WriteLine("" + e);
return new ArrayList();
}
}
return reservations ;
}
答案 1 :(得分:1)
在调用await
方法时,您需要使用async
关键字
reservations = await CheckReservations(currentDate);