Entity Platform NullReferenceException and Multithreading

I save data using the Entity Framework in a Parallel.ForEach loop. Knowing that EF is not thread safe, I define an entity context for each of my threads.

1- Is it safe? It seems I see in these posts:

Entity Framework + multiple threads + lazy loading

Is it possible to use one Entity Framework context for each thread? ... yes? as?

2. At the time of creating my context, there is an exception, but only once out of 3, and I cannot understand why.

Here is my code creating the context:

public partial class Entities { private static Entities mfgEntities = new Entities(); private static readonly Dictionary<int,Entities> ThreadContexts = new Dictionary<int, Entities>(); public static Entities Context { get { if (HttpContext.Current != null) { string objectContextKey = HttpContext.Current.GetHashCode().ToString("x"); if (!HttpContext.Current.Items.Contains(objectContextKey)) { HttpContext.Current.Items.Add(objectContextKey, new Entities()); } return HttpContext.Current.Items[objectContextKey] as Entities; } else { int threadId = Thread.CurrentThread.ManagedThreadId; if (!ThreadContexts.ContainsKey(threadId)) { try { ThreadContexts.Add(threadId, new Entities()); } catch (Exception ex) { throw new Exception("Erreur lors de la création de l'entity context"); } } return ThreadContexts[threadId]; } return mfgEntities; } } } 

It throws a NullReferenceException on the line:

 ThreadContexts.Add(threadId, new Entities()); 

And ThreadContexts, threadId, and new objects are not null.

Thank you for your help.

+4
source share
1 answer

You must use ConcurrentDictionary for ThreadContexts .

Better even: find a way to capture an instance of the context in the stream, for example. by doing parallel tasks :

 var task1 = new Task(() => <your method that instantiates a context>)); 
+1
source

Source: https://habr.com/ru/post/1411552/


All Articles