locked
Getting Must create DependencySource on same Thread as the DependencyObject error RRS feed

  • Question

  • I have an ObservableCollection of a class that contains couple properties, including one of type System.Windows.Media.Imaging.BitmapImage.

    I'm trying to populate the collection using the Parallel library with this code:

    thumbnails = new ObservableCollection<thumbnailClass>();
    String[] files = System.IO.Directory.GetFiles(folderPath);
    
    Parallel.ForEach(files (file) =>
    {
        thumbnails.Add(new thumbnailClass(file))
    });

    And the constructor for thumbnailClass is:

    public thumbnailClass(String imagePath)
       {
          image = new BitmapImage();
          image.BeginInit();
          image.UriSource = new Uri(imagePath);
          image.DecodePixelWidth = 200;
          image.EndInit();
       }

    When I try to use Parallel loops, I'm getting the "Must create DependencySource on the same Thread as the DependencyObject" error.  When I just load the images using a basic foreach loop, no problem.

    Does anyone have any suggestions on how to work around this issue?

    Richard

    Monday, August 31, 2020 8:53 PM

Answers

  • Hi RichardR,

    Thank you for posting here.

    The simplest solution is to freeze the Image object.

                Image = new BitmapImage();
                Image.BeginInit();
                Image.UriSource = new Uri(imagePath);
                Image.DecodePixelWidth = 200;
                Image.EndInit();
               Image.Freeze();

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by RichardR Tuesday, September 1, 2020 5:08 PM
    Tuesday, September 1, 2020 2:34 AM

All replies

  • Hi RichardR,

    Thank you for posting here.

    The simplest solution is to freeze the Image object.

                Image = new BitmapImage();
                Image.BeginInit();
                Image.UriSource = new Uri(imagePath);
                Image.DecodePixelWidth = 200;
                Image.EndInit();
               Image.Freeze();

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by RichardR Tuesday, September 1, 2020 5:08 PM
    Tuesday, September 1, 2020 2:34 AM
  • Timon,

    Thank you -- that did the trick! <G>

    Richard

    Tuesday, September 1, 2020 5:08 PM