异步,等待和奇怪的结果

时间:2014-09-26 14:51:22

标签: c# async-await windows-phone-8.1

我正在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?当我不使用async并等待一切正常时,vm.TimeTableCollection有x个元素。

2 个答案:

答案 0 :(得分: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方法,因此GetTimeTable应为GetTimeTableAsync

答案 1 :(得分:0)

您还没有等待结果:

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

如果你不是await异步方法,程序将执行它,并继续执行以下代码而不等待它完成。

相关问题