2014-09-26 157 views
0

我正在WP 8.1上編寫應用程序。我的一個方法是解析html,一切都很好。但是我想改變編碼來打磨波蘭人。 所以我必須將Length屬性設置爲變量類型byte []。爲了使這成爲可能,我需要使用等待並更改我的方法asnych異步,等待和奇怪的結果

public async void GetTimeTable(string href, int day) 
{ 
    string htmlPage = string.Empty; 
    using (var client = new HttpClient()) 
    { 
     var response = await client.GetByteArrayAsync(URL); 

     char[] decoded = new char[response.Length]; 
     for (int i = 0; i < response.Length; i++) 
     { 
      if (response[i] < 128) 
       decoded[i] = (char)response[i]; 
      else if (response[i] < 0xA0) 
       decoded[i] = '\0'; 
      else 
       decoded[i] = (char)iso8859_2[response[i] - 0xA0]; 
     } 
     htmlPage = new string(decoded); 
    } 

    // further code... and on the end:: 
    TimeTableCollection.Add(xxx); 
} 

public ObservableCollection<Groups> TimeTableCollection { get; set; } 

方法是從MainPage.xaml.cs中

調用
vm.GetTimeTable(navContext.HrefValue, pivot.SelectedIndex); 
TimeTableViewOnPage.DataContext = vm.TimeTableCollection; 

現在是我的問題。爲什麼vm.TimeTableCollection是null?當我不使用異步並等待一切正常時,vm.TimeTableCollection包含x個元素。

+0

您不等待'GetTimeTable',因此控件在完成之前會繼續到下一行。對此,有很多例子。 – 2014-09-26 14:53:19

回答

1

現在是我的問題。爲什麼vm.TimeTableCollection是null?

因爲您正在執行async操作而沒有await它。因此,當您訪問下一行中的vm屬性時,請求可能不完整。

你需要你的方法的簽名更改爲async Taskawait它:

public async Task GetTimeTableAsync(string href, int day) 
{ 
    string htmlPage = string.Empty; 
    using (var client = new HttpClient()) 
    { 
     var response = await client.GetByteArrayAsync(URL); 

     char[] decoded = new char[response.Length]; 
     for (int i = 0; i < response.Length; i++) 
     { 
      if (response[i] < 128) 
       decoded[i] = (char)response[i]; 
      else if (response[i] < 0xA0) 
       decoded[i] = '\0'; 
      else 
       decoded[i] = (char)iso8859_2[response[i] - 0xA0]; 
     } 
     htmlPage = new string(decoded); 
    } 

    // further code... and on the end:: 
    TimeTableCollection.Add(xxx); 
} 

然後:

await vm.GetTimeTableAsync(navContext.HrefValue, pivot.SelectedIndex); 

這意味着你的頂部調用的方法有可能成爲異步爲好。這通常是處理異步方法時的行爲,您需要去async all the way

注意,按照TPL準則,你應該標註任何async方法與Async後綴,因此GetTimeTableGetTimeTableAsync

0

你不等待結果:

await vm.GetTimeTable(navContext.HrefValue, pivot.SelectedIndex); 
TimeTableViewOnPage.DataContext = vm.TimeTableCollection; 

如果你不」 t await一個異步方法,程序將執行它,並繼續執行下面的代碼,而不用等待它完成。