This project has moved. For the latest updates, please go here.
2
Vote

Multi-threaded issue with EFMap

description

Hi,

First, thanks for the libraries. The Bulk Insert is very useful.

I came across a multi-threading issue in EfMap. It uses a dictionary to store generated mappings, populating it on first use. If you have multiple threads that access it at the same time then it can cause issues.

In my case it caused a null reference exception in one of the MappingApiExtensions, I believe this was because two threads can initialise and add definitions to the dictionary at the same time.

Sticking a lock around the add fixed it (see below), although the simplest (and probably safest) fix is just to use ConcurrentDictionary and GetOrAdd()
return Mappings.GetOrAdd(cackeKey, key => new DbMapping(context));
In the meantime, if anyone else has this issue, then forcing the mapping to be generated before any multi-threaded use seems to be a workaround.

Thanks,

Matt.

Lock code:
            if (Mappings.ContainsKey(cackeKey))
            {
                return Mappings[cackeKey];
            }

            lock (MappingsLock)
            {
                if (Mappings.ContainsKey(cackeKey))
                {
                    return Mappings[cackeKey];
                }

                var mapping = new DbMapping(context);
                Mappings[cackeKey] = mapping;
                return mapping;
            }

comments

MattDarg wrote Sep 23, 2015 at 3:21 PM

wrote Mar 23, 2016 at 1:17 PM