“等待"不等待调用完成 [英] "await" doesn't wait for the completion of call

查看:38
本文介绍了“等待"不等待调用完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Metro 应用程序.

I'm building a Metro App.

在 MainPage.xaml.cs 中,我实例化 Album 如下:

In the MainPage.xaml.cs, I instantiate Album as follows:

Album album = new Album(2012);  //With the album ID as its parameter.
ListView1.ItemsSource = album.Songs;

在Album.cs中,构造函数如下:

In the Album.cs, the constructor is as follows:

public Album(int ID)
{
    this.ID = ID;
    Initialize();  //Serves as a wrapper because I have to call httpClient.GetStreamAsync() and "async" doesn't work for the constructor.
}

最后是Initialize方法:

Finally, the Initialize method:

private async void Initialize()
{
    //...some code...
    HttpClient cli = new HttpClient();
    Stream SourceStream = await HttpClient.GetStreamAsync("http://contoso.com");
    //...some code...
    this.Songs = Parse(SourceStream);
}

问题是当它运行到 GetStreamAsync 时,它会直接转到 ListView1.ItemsSource = album.Songs,而专辑.Songs 为空.

The problem is when it runs to GetStreamAsync, it then goes to ListView1.ItemsSource = album.Songs directly with the album.Songs null.

有没有快速解决这个问题的方法?

Is there any quick solution to this problem?

推荐答案

是的.asyncawait 的全部意义在于你不要阻塞.相反,如果您正在等待"一个尚未完成的操作,则会安排一个延续来执行异步方法的其余部分,并将控制权返回给调用者.

Yes. The whole point of async and await are that you don't block. Instead, if you're "awaiting" an operation which hasn't completed yet, a continuation is scheduled to execute the rest of the async method, and control is returned to the caller.

现在因为你的方法有一个 void 类型,你无法知道它什么时候完成 - 如果你返回 Task(不需要任何更改)在方法的主体中)你至少可以在它完成后计算出来.

Now because your method has a type of void, you have no way of knowing when that's even finished - if you returned Task (which wouldn't require any change in the body of the method) you'd at least be able to work out when it had finished.

您的代码是什么样的并不是很清楚,但从根本上说,您应该只在初始化完成后尝试设置 ItemsSource .您可能也应该将 MainPage 代码放在异步方法中,看起来像:

It's not really clear what your code looks like, but fundamentally you should only be trying to set the ItemsSource after initialization has finished. You should probably have your MainPage code in an async method too, which would look something like:

Album album = new Album(2012);
ListView1.ItemsSource = await album.GetSongsAsync();

您的 GetSongs() 调用将是:

private async Task<List<Song>> GetSongsAsync()
{
    //...some code...
    HttpClient cli = new HttpClient();
    Stream SourceStream = await HttpClient.GetStreamAsync("http://contoso.com");
    //...some code...
    return Parse(SourceStream);
}

这意味着 Songs 将不再是 Album 本身的属性,尽管您可以根据需要将其添加到缓存中.

This means Songs would no longer be a property of Album itself, although you could add it in for caching purposes if you wanted to.

这篇关于“等待"不等待调用完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆