magna_nz magna_nz - 10 days ago 11
C# Question

ContinueWith not waiting for task to complete

I have a function (below) that I retrieve data from an API. If I set a breakpoint at the line that deserializes it, then I can see that it is populated with data which is great.

When I continue on, it goes into the second function (below) and it throws an error. The error says next to it

Not yet computed
, and therefore throwing an exception.

When I do it with a small list it works just fine (I presume its cos it's a small set of data).

How is this possible when I'm using
ContinueWith
(waiting for the task to complete)?

public static async Task<Data> GetAllCardsInSet(string setName)
{
setName = WebUtility.UrlEncode(setName);
var correctUri = Path.Combine(ApiConstants.YugiohGetAllCardsInSet, setName);
Console.WriteLine();
using (var httpClient = new HttpClient())
{
var response =
await httpClient.GetAsync(correctUri);
var result = await response.Content.ReadAsStringAsync();
var cardData = JsonConvert.DeserializeObject<CardSetCards>(result);
for (int i = 0; i < cardData.Data.Cards.Count; i++)
{
cardData.Data.Cards[i] = FormatWords(cardData.Data.Cards[i]);
}
return cardData.Data;
}
}


private void GetYugiohCardsAndNavigate(string name)
{
var cardSetData = YugiohRequester.GetAllCardsInSet(_selectedCardSet.Name).ContinueWith((result) =>
{
//var cards = await YugiohRequester.GetAllCardsInSet(_selectedCardSet.Name);
try
{
this.mainPage.NavigateToYugiohCardListPage(result.Result);
}
catch (Exception e)
{
HelperFunctions.ShowToastNotification("Trading Card App", "Sorry, we could not fetch this set");
}

});
}

Answer

Your GetAllCardsInSet method no need to change.
But using of this method can be refactored.
Method GetAllCardsInSet return Task and you not observed the completion of the this Task.
You need to check is Task completes succesfully, easiest approach to use await keyword. Awaiting task will unwrapp returned value or throw exception if task completed with exception.

For using async/await in the GetYugiohCardsAndNavigate change method signature to aynchronous and returning Task

private async Task GetYugiohCardsAndNavigate(string name)
{
    try
    {
        var cardSetData  = await YugiohRequester.GetAllCardsInSet(_selectedCardSet.Name);
        this.mainPage.NavigateToYugiohCardListPage(cardSetData);
    }
    catch (Exception e)
    {
        HelperFunctions.ShowToastNotification("Trading Card App", 
                                              "Sorry, we could not fetch this set");
    }
}