"&AWAIT QUOT;不等待调用完成

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

我要建地铁的应用程序。

I'm building a Metro App.

在MainPage.xaml.cs中,我实例专辑如下:

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. }

最后,初始化方法:

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直接与album.Songs空。

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

有没有快速的解决这个问题? THX在前进。

Is there any quick solution to this problem? Thx in advance.

推荐答案

是的。 的异步和等待整点是,你的不的块。相反,如果你是等待,它尚未完成的操作,继续按计划执行异步方法的其余部分,并控制返回给调用者。

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.

现在,因为你的方法有一个类型无效,你无法知道当这样就算完了的方式 - 如果你回到工作(这不会需要在方法体中的任何变化),你会至少能够制定出时,它已经完成了。

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.

这不是真的清楚你的code看起来像什么,但是从根本上,你应该只尝试设置的ItemsSource 的之后的初始化完了。你应该有你的的MainPage code在异步方法也一样,它看起来是这样的:

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); }

这将手段歌曲将不再是专辑本身的属性,虽然你可以将它添加了缓存目的,如果你想。

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

更多推荐

&QUOT;&AWAIT QUOT;不等待调用完成

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

发布评论

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

>www.elefans.com

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