Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing dictionary items instantiated in child thread

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.

like image 922
Gavimoss Avatar asked Feb 12 '12 01:02

Gavimoss


1 Answers

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.

like image 175
Marcin Deptuła Avatar answered Nov 18 '22 08:11

Marcin Deptuła