phm
phm

Reputation: 1170

WPF dispatcher/threading issue

I have a problem in my code and I am not able to fix it at all.

private static void SetupImages(object o)
    {
        int i = (int)o;
        BitmapImage bi = GetBitmapObject(i);
        img = new System.Windows.Controls.Image();//declared as static outside

        img.Source = bi;//crash here
        img.Stretch = Stretch.Uniform;
        img.Margin = new Thickness(5, 5, 5, 5);
    }

which is called like this:

for (int i = 0; i < parameters.ListBitmaps.Count; i++)
        {
            ParameterizedThreadStart ts = new ParameterizedThreadStart(SetupImages);
            Thread t = new Thread(ts);
            t.SetApartmentState(ApartmentState.STA);
            t.Start(i);
            t.Join();
            //SetupImages(i);
            parameters.ListImageControls.Add(img);
        }

It always crashes on this line: img.Source = bi; The error is: "An unhandled exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll

Additional information: The calling thread cannot access this object because a different thread owns it."

Thanks

Upvotes: 0

Views: 1747

Answers (2)

Kent Boogaart
Kent Boogaart

Reputation: 178790

Objects descending from DispatcherObject have thread affinity. This means that (most) of their properties and methods cannot be accessed from any thread apart from the thread on which the object was created.

Where does the BitmapImage come from? Who creates it and on which thread?

I think what you're trying to do can probably done much simpler if you explain what it is you're trying to achieve.

Upvotes: 1

Sergey Galich
Sergey Galich

Reputation: 243

as already mentioned BitmapImage can be used only in the thread where it was created.

If you load many small sized images, then you can load images to MemoryStream in background thread. Once you have data in memory, switch to UI thread and set StreamSource:

image.StreamSource = new MemoryStream(data);

Upvotes: 2

Related Questions