4

So in my DoWork, I have

List<KeyValuePair<String, BitmapImage>> Files = new List<KeyValuePair<string,BitmapImage>>((List<KeyValuePair<String, BitmapImage>>)e.Argument);

foreach (KeyValuePair<String, BitmapImage> i in Files)
{
    string temp = i.ToString();               .......(1)
    //.....
}

I'm passing the argument as follows :-

backgroundWorkerForReupload.RunWorkerAsync(files);

where "files" is of Type List<KeyValuePair<string, BitmapImage>>

At line (1) above, it throws an InvalidOperationException with the message : "The calling thread cannot access this object because a different thread owns it."

I'm confused as to why i is owned by another thread. Any help would be greatly appreciated. Thank you.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
AyushISM
  • 381
  • 7
  • 21
  • How were they loaded? Were they used for anything else? Most likely reason is that they are somehow associated with the main UI thread. – toad Jan 24 '14 at 21:00
  • `e.Argument` is where this is coming from. The argument is coming from the calling thread. Thereby, although you are creating a new list of key value pairs, the data contained in these pairs is not copied, it is referenced, and on another thread. Still doesn't explain why the thread safe call to `ToString` fails. – Will Custode Jan 24 '14 at 21:01
  • 1
    @toad the original List is being used in the UI thread but "Files" is created using the new keyword (in the DoWork() method). So shouldn't it be a new copy of the list owned by the background thread? – AyushISM Jan 24 '14 at 21:03

1 Answers1

4

Most WPF objects, including BitmapImage, are thread-affine, and can only be used by the thread they were created on.

You can fix this for BitmapImage by calling Freeze() first.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thank you sir your solution has helped me a lot, actually I been searching for a solution for this problem on this thread : http://stackoverflow.com/questions/23975709/invalidoperationexception-when-trying-to-access-a-complex-object-from-another-th/23979622#23979622 – Ibrahim Amer Jun 01 '14 at 13:33