Sign in to follow this  

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

This topic is 2838 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
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

This topic is 2838 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this