Error in "Music Store App" Tutorial Information #322
francisco-chavez
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
On the "Load Cover Art" section of the "Displaying Image" page of the "Music Store App" tutorial, there is a Warning section stating that we are doing are copying the SearchResults into a list to load the cover images into their own thread. That's not the reason why we need to copy the contents of SearchResults.
When running as a Windows Desktop app, some of the code does execute on threads other than the main-thread, but that's only parts of the code.
The
GetByteArrayAsync(...)
method has parts that might execute on a different thread (this is platform specific). Otherwise, it executes on the thread that called it. It won't block the thread that called it, but that's not the same thing as not running on the thread that calls it.In AlbumViewModel.cs, there's the call to
Bitmap.DecodeToWidth(imageStream, 400)
; this will execute in a different thread because it executes inside ofTask.Run(...)
. But, the rest of the image loading code (with is most of said code) will execute on the main-thread.Now, due to all of the
awaits
that we throw around, the code for loading the images releases execution of the main-thread often enough, that it remains responsive to the User. Yet, this code resumes execution on the main-thread. You can check this in Visual Studio. I know that I did.Now, there is still a good reason for running the foreach loop on a copy of the SearchResults inside of
MusicStoreViewModel.LoadCovers(...)
. Since we release control of the main-thread multiple times during the execution of the foreach loop, the contents of SearchResults can be changed before we have finished executing the foreach loop. In C#, changing the contents of a collection as it is being iterated over by a foreach loop will throw an exception. And, since SearchResults can be changed during awaits (because that's when we temporally release control of the main-thread), we can not do a foreach loop over the SearchResults collection without some exception handling and exception recovery code. Running off of a copy of SearchResults stops us from getting an exception if SearchResults happens to change while we're still loading images.Beta Was this translation helpful? Give feedback.
All reactions