Jump to content
  • Advertisement
Sign in to follow this  
Side Winder

[.net] [C#, WPF] Multi-threaded woes

This topic is 3053 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm creating an application where I have many photos on display at once. My problem is loading them in a suitable manner. I want to have it in a similar way as Windows Explorer does. As in, when the user clicks on a folder/album the thumbnails will be loaded on a background thread, and as a photo gets loaded, the UI reflects the change. I only want this when the user SELECTS that folder though; so when they de-select a folder, the thumbnails that were loaded, will be... err.. un-loaded. Is that even possible? In my photo class I have a Source property that is of type ImageSource. The XAML uses this property. So what would be the best solution to this problem? I just tried using a BackgroundWorker but it says the object (I guess the photo object) belongs to a different thread so it can't change (i.e. load the thumbnail) the Source property. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
You have to freeze the image to be able to use it across threads. You can then use the Window's or UserControl's Dispatcher to move it to the main thread where your UI can access it:


void worker_DoWork(object sender, DoWorkEventArgs e) {
foreach (string file in Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg")) {
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(file, UriKind.Absolute);
img.EndInit();
img.Freeze();

Photo photo = new Photo() { Source = img };
this.Dispatcher.Invoke(new Action(() => {
this.Photos.Add(photo);
}));
}
}

Share this post


Link to post
Share on other sites
You're welcome. Oh and Dispatcher.BeginInvoke would probably make more sense in my example.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!