ContinueWith没有被称为async

本文关键字:async 被称为 ContinueWith | 更新日期: 2023-09-27 18:01:58

在执行语句中的下一行之前,我试图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;
                }
            }
        }

为什么我的代码不进入ContinueWith时,我有JSON ?谢谢!

ContinueWith没有被称为async

不只是分配热门任务,而是等待它完成。您必须在该任务上调用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;