“等待"不等待调用完成

编程入门 行业动态 更新时间:2024-10-26 20:27:39
本文介绍了“等待"不等待调用完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在构建一个 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("contoso"); //...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?

推荐答案

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

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("contoso"); //...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.

更多推荐

“等待"不等待调用完成

本文发布于:2023-11-06 10:00:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563384.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!