Throw a NullReferenceException while calling the set_item method of a Dictionary object in a multi-threading scenario

As the exception occurs internally in the Dictionary code, it means that you are accessing the same Dictionary instance from more than one thread at the same time.

You need to synchronise the code in the GetInstance method so that only one thread at a time accesses the Dictionary.

Edit:
Lock around the accesses separately, so that you aren’t inside a lock while doing the (supposedly) time consuming loading:

private static object _sync = new object();

public static object GetInstance(string key) {
   object instance = null;
   bool found;
   lock (_sync) {
      found = Instances.TryGetValue(key, out instance);
   }
   if (!found) {
      instance = LoadInstance(key);
      lock (_sync) {
         object current;
         if (Instances.TryGetValue(key, out current)) {
            // some other thread already loaded the object, so we use that instead
            instance = current;
         } else {
            Instances[key] = instance;
         }
      }
   }
   return instance;
}

Leave a Comment