在执行语句中的下一行之前,我正在尝试获取一些值。我需要等待这个调用返回,以便我可以使用我反序列化为一个列表的值。
由于我希望异步调用首先完成,所以我将其包装在一个Task中。它工作了,并且正在成功地检索JSON。然后,我无法让它进入ContinueWith块。即使任务完成了,为什么它也不进去呢?
我怎么称呼它:
Task f = Task.Run(() =>
{
var task = RetrieveDataAsync();
}).ContinueWith((antecedent) =>
{
pokemonListActivityListView.Adapter = new PokemonListAdapter(this, pokemonList);
pokemonListActivityListView.FastScrollEnabled = true;
pokemonListActivityListView.ItemClick += PokemonListActivityListViewOnItemClick;
});RetrieveDataAsync方法:
private async Task RetrieveDataAsync()
{
string dataUri = "http://pokemonapp6359.azurewebsites.net/Pkmn/GetAllPokemon";
using (var httpClient = new HttpClient())
{
var uri = new Uri(string.Format(dataUri, string.Empty));
//DisplayProgressBar(BeforeOrAfterLoadState.Before, progressBarView);
var response = await httpClient.GetAsync(uri);
//DisplayProgressBar(BeforeOrAfterLoadState.After, progressBarView);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
pokemonList = JsonConvert.DeserializeObject<List<PokemonDTO>>(content);
//canPressButtons = true; //fix this when implement local db
Utilities.Utilities.ShowToast(this, "Successfully fetched data", ToastLength.Short, GravityFlags.Center);
return;
}
else
{
Utilities.Utilities.ShowToast(this, "Failed to fetch data", ToastLength.Short, GravityFlags.Center);
return;
}
}
}当我得到JSON时,为什么我的代码不进入ContinueWith?谢谢!
发布于 2016-08-11 08:55:53
而不是仅仅分配热任务,您没有等待它完成。您必须在此任务上调用ContinueWith:
var task = RetrieveDataAsync();
task.ContinueWith( ... );或等待任务:
var result = await RetrieveDataAsync();
... // continue发布于 2016-08-11 12:56:36
问题是您忽略了从RetrieveDataAsync返回的任务。如果您从lambda表达式返回该任务,那么它将按照您的预期运行。
另外,您不应该使用ContinueWith;这是一个危险的API。使用await而不是ContinueWith
await Task.Run(() => RetrieveDataAsync());
pokemonListActivityListView.Adapter = new PokemonListAdapter(this, pokemonList);
pokemonListActivityListView.FastScrollEnabled = true;
pokemonListActivityListView.ItemClick += PokemonListActivityListViewOnItemClick;https://stackoverflow.com/questions/38891667
复制相似问题