I'm currently grappling with threads and hoping that someone can clearly explain how to resolve the following error.
I have a global Dictionary<string, BitmapImage> dic
which I instantiate in the main thread.
The main thread creates a child thread to populate the dictionary with images.
The main thread then tries to access the dictionary and throws an exception
The calling thread cannot access this object because a different thread owns it
I have no issues accessing the dictionary itself e.g. dic.ContainsKey("key")
works just fine, it's just when I try to access a BitmapImage
in the dictionary that the error occurs.
I'm guessing it's because BitmapImages stored in the dictionary are instantiated in the child thread and it's causing an issue - any ideas how I can get around this?
I've looked at loads of threading tutorials and advice here but it seems like everywhere else tells you how to access a parent thread object from a child thread whereas I'm trying to do the opposite.
Thanks.
In general, you can only access UI elements from the thread they were created. Which means, you should make sure that main thread is creating BitmapImage
objects by itself.
However, in this case, you might use the fact, that BitmapImage
can be used from different threads after they have been frozen (with Freeze() method). You can therefore try to create images on child threads, freeze them and then add them to your dictionary (make sure you do it in thread safe manner, for example by locking some mutex object before accessing dictionary).
More info can be found on Freezeable Objects Overview site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With