实体框架新事务不允许,因为会话中还有其他线程运行,多线程保存 [英] Entity Framework new transaction is not allowed because there are other threads running in the session, multi thread save
问题描述
我是tryng,以保存DB的多线程进程的日志,但我收到以下错误:新事务是不允许的,因为会话中还有其他线程。
I'm tryng to save on a DB the log of a multi thread processo but I'm getting the following error: new transaction is not allowed because there are other threads running in the session.
在每个步骤我有这个功能:
in each tread I have this function:
internal bool WriteTrace(IResult result, string message, byte type)
{
SPC_SENDING_TRACE trace = new SPC_SENDING_TRACE(
message,
Parent.currentLine.CD_LINE,
type,
Parent.currentUser.FULLNAME,
Parent.guid);
Context.SPC_SENDING_TRACE.AddObject(trace);
if (Context.SaveChanges(result) == false)
return false;
return true;
}
每个线程的上下文不同,但与数据库总是一样的。
the Context is different for each thread, but the connection with the DB is always the same.
有没有办法解决这个问题?
is there a way to solve this problem?
谢谢
Andrea
thank you Andrea
推荐答案
您应该为每个事务创建一个上下文,然后处理它,您可以这样做:使用(var ctx = new MyContext()){
// do transaction here
} $ b $($)
You should create a context for each transaction and then dispose it, you can do that like this:
using(var ctx = new MyContext()) {
//do transaction here
}
关闭括号后,上下文处理。
After the closed bracket the context is disposed.
为了更好地了解,请参阅此信息在哪里可以通过 ken2k 找到一个很好的答案。希望你可以解决你的问题:)
For better understanding refer to this post where you can find a great answer by ken2k. Hope you can fix you issue :)
更新:
尝试向您拥有的每个LINQ查询添加 .ToList()
。当迭代LINQ结果时,直到迭代完成后,才能进行任何更改。检查你是否有这样的东西,或者分享更多的代码,即你所调用的代码 WriteTrace
。希望这次这实际上可以帮助你。
You should also try adding .ToList()
to every LINQ query you have. When you iterate over a LINQ result, you can't make any changes until the iteration has finished. Check if you have something like that or share more code i.e. the piece of code where you call WriteTrace
. Hope that this time this actually helps you.
这篇关于实体框架新事务不允许,因为会话中还有其他线程运行,多线程保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!