ContinueWith没有被称为异步

时间:2016-08-11 08:54:05

标签: c# android .net asynchronous

我在执行语句中的下一行之前尝试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?谢谢!

2 个答案:

答案 0 :(得分:1)

不是仅仅分配热门任务,而是等待它完成。您必须在该任务上致电ContinueWith

var task = RetrieveDataAsync();
task.ContinueWith( ... );

等待任务:

var result = await RetrieveDataAsync();

... // continue

答案 1 :(得分:1)

问题在于您忽略了从RetrieveDataAsync返回的任务。如果您从lambda表达式中返回该任务,那么它将按预期运行。

另一方面,你不应该使用ContinueWith;这是一个危险的API。使用await代替ContinueWith

await Task.Run(() => RetrieveDataAsync());
pokemonListActivityListView.Adapter = new PokemonListAdapter(this, pokemonList);
pokemonListActivityListView.FastScrollEnabled = true;
pokemonListActivityListView.ItemClick += PokemonListActivityListViewOnItemClick;