异步,等待和奇怪的结果

问题描述:

我正在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

现在是我的问题。为什么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

你不等待结果:

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

如果你不” t await一个异步方法,程序将执行它,并继续执行下面的代码,而不用等待它完成。