[英]ContinueWith not being called async
在嘗試執行語句的下一行之前,我嘗試httpget一些值。 我需要等待此調用返回,以便可以將反序列化的值使用到列表中。
由於我希望異步調用首先完成,因此將其包裝在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
? 謝謝!
您不必等待它完成,而不僅僅是分配熱任務。 您必須在該任務上調用ContinueWith
:
var task = RetrieveDataAsync();
task.ContinueWith( ... );
或等待任務:
var result = await RetrieveDataAsync();
... // continue
問題是您忽略了RetrieveDataAsync
返回的任務。 如果您從lambda表達式返回該任務,則它將按預期運行。
附帶說明一下,您不應該使用ContinueWith
; 這是一個危險的API。 使用await
代替ContinueWith
:
await Task.Run(() => RetrieveDataAsync());
pokemonListActivityListView.Adapter = new PokemonListAdapter(this, pokemonList);
pokemonListActivityListView.FastScrollEnabled = true;
pokemonListActivityListView.ItemClick += PokemonListActivityListViewOnItemClick;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.