Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by Side Winder Mar 9, 2010 at 5:21 PM 2 replies 1.5k views
Original Post
Side Winder
Side Winder
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.
itachi
itachi
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);		}));	}}
Side Winder
Side Winder
Works perfectly, thank you.
itachi
itachi
You're welcome. Oh and Dispatcher.BeginInvoke would probably make more sense in my example.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.