views:

101

answers:

2

Hello

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

+1  A: 

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.

HTH,
Kent

Kent Boogaart
Thanks for the answer.The BitmapImage is coming from here:private static BitmapImage GetBitmapObject(int nPos) { return parameters.ListBitmaps[nPos]; }I am trying to load some bitmap files from disk and add them to a grid. I need to do this in a thread so I can update a status window while the images are loading.
phm
+2  A: 

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);

Sergey Galich