c# - Entity Framework new transaction is not allowed because there are other threads running in the session,多线程保存

标签 c# multithreading entity-framework-4 savechanges

我正在尝试将多线程进程的日志保存在数据库中,但出现以下错误:不允许新事务,因为 session 中还有其他线程在运行。

在每个胎面我都有这个功能:

 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;

    }

每个线程的上下文不同,但与数据库的连接始终相同。

有没有办法解决这个问题?

谢谢 安德里亚

最佳答案

您应该为每个事务创建一个上下文然后处理它,您可以这样做:

using(var ctx = new MyContext()) {
    //do transaction here
}

在右括号之后处理上下文。

为了更好地理解,请参阅 this post在这里你可以找到一个很好的答案 ken2k .希望你能解决你的问题:)

更新:

您还应该尝试将 .ToList() 添加到您拥有的每个 LINQ 查询中。迭代 LINQ 结果时,在迭代完成之前不能进行任何更改。检查您是否有类似的东西或共享更多代码,即您调用 WriteTrace 的代码段。希望这次这真的能帮到你。

关于c# - Entity Framework new transaction is not allowed because there are other threads running in the session,多线程保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15363242/

相关文章:

java - 使用 TCP KeepAlive 检测套接字断开连接

c# - 代码优先 POCO 设计

c# - 如何在linq中加入4个表

C# 允许用户输入条件规则

c# - 设置环境变量

java - 什么时候在 Java 中选择多个进程而不是线程?

multithreading - Delphi-线程中的消息泵未接收到WM_COPYDATA消息

sql-server - 具有 LEFT OUTER JOIN 的 SQL Server 2008 View 在 Entity Framework 4 上失败

c# - 信箱不可用。服务器响应是 : No such domain at this location

c# - 使用 Linq 进行复制/过滤会在 foreach 循环中产生动态结果吗?