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