2016-11-30 230 views
0

我有一個函數(下),我從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"); 
        } 

       }); 
} 
+0

如果你避開'ContinueWith'只是等待'GetAllCardsInSet'方法是什麼會事? – kat1330

+0

給我一個空引用異常 –

+0

如果你返回'await Task.FromResult(cardData.Data)'而不是'cardData.Data',你能否調查一下會發生什麼? – kat1330

回答

2

您的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"); 
    } 
} 
0

您在同步方法中調用了異步方法,但沒有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();