Threading errors with Application.LoadComponent (key already exists) Threading errors with Application.LoadComponent (key already exists) wpf wpf

Threading errors with Application.LoadComponent (key already exists)


You are not doing something wrong. MSDN is wrong. Application.LoadComponent is not actually thread safe. This is a bug in WPF, in my opinion.

The problem is that whenever Application.LoadComponent loads a "Part" from a "Package" it:

  1. Checks its internal cache for the package to see if the part is already loaded & returns it if found
  2. Loads the part from the file
  3. Adds it to the internal cache
  4. Returns it

You have two threads calling Application.LoadComponent to load the same part at the same time. The MSDN documentation says this is ok, but what is happening is:

  1. Thread #1 checks the cache and starts loading from the file
  2. Thread #2 checks the cache and starts loading from the file
  3. Thread #1 finishes loading from the file and adds to the cache
  4. Thread #2 finishes loading from the file and tries to add to the cache, resulting in a duplicate key exception

The workaround for the bug is to wrap all calls to Application.LoadComponent inside a lock().

Your lock object can be created thusly in your App.cs or elsewhere (your choice):

 public static object MyLoadComponentLock = new Object();

Then your LoadComponent call looks like this:

 lock(App.MyLoadComponentLock)   genericDictionary = (ResourceDictionary)Application.LoadComponent(...


It looks like an item with the same key has already been added in the map. It's not a threading issue, it's an issue with the program you have. One thread has added a key/value pair to the map and a second thread is attempting to add a value with an identical key, how did you end up having identical keys on two separate threads? How are you generating the keys?

The elements of a SortedList objectare sorted by the keys eitheraccording to a specific IComparerimplementation specified when theSortedList is created or according tothe IComparable implementationprovided by the keys themselves. Ineither case, a SortedList does notallow duplicate keys.

(from the msdn documentation)

Update:
Try synchronizing when you're calling LoadComponent and see if the issue still persists.

I simply don't know what they mean when they say the following:

The public static (Shared in VisualBasic) members of this type are threadsafe. In addition, the FindResourceand TryFindResource methods and theProperties and Resources propertiesare thread safe.

It sure does say thread safe, but if it's duplicating identical keys, then they must be referring to some other type of thread safety.