[英]NullReferenceException with Entity Framework and Multithreading
I'm saving data using the Entity Framework in a Parallel.ForEach loop. 我在Parallel.ForEach循环中使用Entity Framework保存数据。 Knowing that the EF is not thread-safe, I instanciate an entity context for each of my thread.
知道EF不是线程安全的,我为每个线程实例化一个实体上下文。
1- Is it safe? 1-安全吗? It seems to be as I see in these posts:
这似乎就像我在这些帖子中看到的那样:
Entity Framework + Multiple Threads + Lazy Load 实体框架+多线程+延迟加载
Is it safe to use one Entity Framework Context per thread? 每个线程使用一个实体框架上下文是否安全? ... yes?
......是的? how?
怎么样?
2-There is an exception during the creation of my context, but only one time out of 3 and I can't found out why. 2 - 在创建我的上下文时有一个例外,但只有一次在3中,我无法找到原因。
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 line : 它在行上抛出NullReferenceException:
ThreadContexts.Add(threadId, new Entities());
And ThreadContexts, threadId and the new Entities are not null. 而ThreadContexts,threadId和新实体不为空。
I thank you for your help. 谢谢你的帮助。
You should use a ConcurrentDictionary
for ThreadContexts
. 您应该为
ThreadContexts
使用ConcurrentDictionary
。
Better even: find a way to capture a context instance in a thread, eg by executing parallel tasks : 甚至更好:找到一种方法来捕获线程中的上下文实例,例如通过执行并行任务 :
var task1 = new Task(() => <your method that instantiates a context>));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.