0

[C#] "Cannot access object, because another thread owns it."

I'm writing a game in C# WPF (must), and my logic runs in its own thread. The main thread invalidates visuals and handles window, the basic stuff. I've got a Resources class with provides static access to loaded images (BitmapImage) with string id's from a Dictionary. The problem is, that when game logic thread gets a resource from it, it throws exception with the given message, as I saw, the Dictionary is the object which is "owned by another thread". Any ways to access the static Dictionary threadsafe?

28th Nov 2016, 3:49 PM
Magyar Dávid
Magyar Dávid - avatar
4 ответов
+ 7
This is often a common problem if you are just getting started. Whenever you update your user interface elements from a thread(excluding the main thread), you need to do these: this.Dispatcher.Invoke(() => { /*Place your code here*/ }); Alternatively, control.Dispatcher.CheckAccess() also works as it helps you to check whether the current thread owns the control. If it does own it, your code will look normal(test it and you will see what I mean by adnormal) .Otherwise, use the above method.
28th Nov 2016, 3:57 PM
Wen Qin
Wen Qin - avatar
0
I'm not updating my user interface, and this is where I get lost. I found this Dispatcher stuff already, and can understand, that the visualisations can run only on the main thread. But I've got nothing to do with the UI itself. I initialize an object in the logic thread which then gets the resource to store it in its static variable for later use. Clearly no UI here :c public static class Resources { private static Dictionary<string, BitmapImage>... ... public static BitmapImage Get(string id) {...} } class Player { ... static BitmapImage img = Resources.Get("player"); } EDIT: May the main thread uses the Resources class first and initializes the Dictionary object, but does the main thread lock all objects it initialize? Can I create a static threadsafe class (where I do the sync myself), if not, why not?
28th Nov 2016, 4:23 PM
Magyar Dávid
Magyar Dávid - avatar
0
I'm not even having: this.Dispatcher (Resources.Dispatcher) neither: Dictionary.Dispatcher There is no "control", but a static class, a static Dictionary, and a Thread which calls the Get() method to access the given resource from the static dictionary. So, how should I use the code you wrote above?
28th Nov 2016, 5:19 PM
Magyar Dávid
Magyar Dávid - avatar
0
Okay, I found the problem, not the Dictionary class, but the BitmapImage is the object, which must be passed that way, and the BitmapImage class does have Dispatcher property. Endlessly found it, thanks~
30th Nov 2016, 9:37 AM
Magyar Dávid
Magyar Dávid - avatar