“await” doesn't wait for the completion of call

后端 未结 2 593
暗喜
暗喜 2021-01-30 11:32

I\'m building a Metro App.

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

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


        
相关标签:
2条回答
  • 2021-01-30 11:59

    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.

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

    Your GetSongs() call would then be:

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

    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.

    0 讨论(0)
  • 2021-01-30 12:02

    Make Songs property return Task<List<Song>> and await at ListView1.ItemsSource = await album.Songs;

    0 讨论(0)
提交回复
热议问题