"Waiting" does not wait for the call to end

I am creating a Metro application.

In MainPage.xaml.cs, I create an album as follows:

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

In Album.cs, the constructor looks like this:

 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("http://contoso.com"); //...some code... this.Songs = Parse(SourceStream); } 

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

Is there a quick fix to this problem? thanks in advance.

+12
c # asynchronous
02 Sep
source share
2 answers

Yes. The whole point of async and await is that you are not blocking. Instead, if you are โ€œexpectingโ€ an operation that is not yet completed, a continuation is scheduled to execute the rest of the async method, and control returns to the caller.

Now, since your method is of type void , you cannot find out when it is still over - if you returned Task (which would not require any changes to the body of the method), you would at least be able to work when it is finished.

It's not entirely clear what your code looks like, but in the root you should only try to set the ItemsSource after initialization is complete. You should probably have your MainPage code in an asynchronous method that looks something like this:

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

Your call to GetSongs() will be as follows:

 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 that Songs will no longer be a property of Album itself, although you can add it for caching purposes if you want.

+25
Sep 02
source share

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

+4
Sep 02
source share



All Articles