I'm developing an app for UWP.
I need to load a folder that contains around 700 small pictures. This is the method I use to load the pictures into memory:
private async Task<ObservableCollection<ImageSource>> LoadPicturesAsync()
{
var pictureList = new ObservableCollection<ImageSource> { };
pictureFiles.ForEach(async file =>
{
var img = new BitmapImage();
pictureList.Add(img);
var stream = await file.OpenReadAsync();
await img.SetSourceAsync(stream);
});
return pictureList;
}
When this method gets called by the constructor of my view model, the view seems to be blocked (unresponsive) for about 6 seconds.
This is strange because all IO operations are done asynchronously, and the only thing running in UI thread is creating of BitmapImage objects in a foreach loop. This is so fast it shouldn't block the UI thread.
My question is: Why did the UI thread block for 6 seconds knowing that I run all IO operations asynchronously? And how to fix this so UI thread is not blocked?
This is how I call that method:
private async Task Init()
{
PictureList = await LoadPicturesAsync();
}
//constructor
public MainVewModel(){
Init();
}