ContinueWith没有等待任务完成
问题描述:
我有一个函数(下),我从API中检索数据。如果我在反序列化它的行上设置断点,那么我可以看到它填充了很好的数据。ContinueWith没有等待任务完成
当我继续,它进入第二个函数(下面),它会引发错误。该错误在它旁边说Not yet computed
,因此抛出异常。
当我用一个小列表做它时,它工作得很好(我认为它的cos它是一小组数据)。
当我使用ContinueWith
(等待任务完成)时,这怎么可能?
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");
}
});
}
答
您的GetAllCardsInSet
方法无需更改。
但这种方法的使用可以重构。
方法GetAllCardsInSet
返回Task
和你没有观察到这个Task
完成。
您需要检查是Task
成功完成,最简单的方法是使用await
关键字。等待任务将解包返回的值或抛出异常,如果任务完成但有异常。
对于在GetYugiohCardsAndNavigate
改变方法签名使用async/await
到aynchronous和返回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");
}
}
答
您在同步方法中调用了异步方法,但没有Wait
。它应该是这样做的:
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");
}
}).Wait();
如果你避开'ContinueWith'只是等待'GetAllCardsInSet'方法是什么会事? – kat1330
给我一个空引用异常 –
如果你返回'await Task.FromResult(cardData.Data)'而不是'cardData.Data',你能否调查一下会发生什么? – kat1330