Good, comrades, advise how best to build logic (if possible with examples).

Given : path to the directory. It is necessary to display in the ListBox (or any other similar component, if the other is easier and easier) images from this directory.

Problems : not all images have thumbnails, this time. Images can be large (up to 20 mb) and there can be a hundred of them. How to make it all this would not hang the application when loading.

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

To begin with, reading the file system must necessarily occur in a separate thread or via async / await. Numerous examples on the Internet are wrong with reading data in the main stream (and almost in OnClick ).

First, separate the UI and logic. In UI, simply bind to ObservableCollection<ImageVM> , and calmly load pictures in the background.

For the VM part, the collection is empty for starters. Go to the separate thread-pool-stream directory:

 var imageFiles = await Task.Run(() => Directory.GetFiles(dir, "*.jpg")); foreach (var f in imageFiles) { BitmapImage img = await Task.Run(() => LoadImage(f)); ImageVM imageVM = new ImageVM(img); ImageCollection.Add(imageVM); } 

Here, the LoadImage code must load a picture asynchronously or create a thumbnail. For example (this is without a size check):

 BitmapImage LoadImage(string path) { BitmapImage s = new BitmapImage(); s.BeginInit(); s.UriSource = new Uri(Path.GetFullPath(path)); s.CacheOption = BitmapCacheOption.OnLoad; s.EndInit(); s.Freeze(); return s; } 

If there are many pictures, and the list itself does not “fly” after downloading, use virtualization .


An alternative solution may be to use PriorityBinding .

  • As far as I understand, this is net 4.5? And only PriorityBinding is younger? - Victor
  • @ Victor: Yes, it is 4.5. For younger versions, I would use BackgroundWorker to read the pictures and deliver them one by one to the main thread. - VladD
  • @ Victor: And do not forget to reduce the image to normal size! And then 100 huge pictures will fill your memory. - VladD
  • Thanks, it helped. - Victor