不允许新事务,因为会话中还有其他线程在运行 [英] New transaction is not allowed because there are other threads running in the session

查看:19
本文介绍了不允许新事务,因为会话中还有其他线程在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取不允许新事务,因为会话中还有其他线程在运行".

Getting "new transaction is not allowed because there are other threads running in the session".

这与 foreach 循环或人们通常在与此消息相关时遇到的任何问题无关.

It has nothing to do with foreach loops or anything people usually have problems with in conjunction with this message.

我使用带有存储库模式和公共上下文的 EF4 在整个请求中打开.发生了一些事情,无法确定到底是什么,当我尝试跨请求保存上下文的更改时,我会立即收到此消息,并且只有在我回收应用程序池后它才会消失.

I using a EF4 with a repositoy pattern and common context open throughout the request. Something happens, can't determine exactly what, and I get this message as soon as I try to savechanges with the context, across requests, and it only dissappears once I recycle the app pool.

我要关闭连接吗?我怎么知道?我是否对每个请求都使用了新的上下文?是的.

Am I closing the connection? How can I tell? Am I using a fresh context for every request? Yes.

发生了什么事?有解决办法吗?

What's going on? Is there a work-around?

(上下文工厂)

    private static Dictionary<string, CoinEntities> _instances;

    public static CoinEntities DefaultInstance
    {
        get
        {
            if (HttpContext.Current == null)
            { //todo: mock instead. testing.
                if (!Instances.ContainsKey("_TEST"))
                    Instances["_TEST"] = new CoinEntities();
                return Instances["_TEST"];
            }

            if (!Instances.ContainsKey("_DEFAULT"))
                Instances["_DEFAULT"] = new CoinEntities();

            return Instances["_DEFAULT"];
        }
    }

推荐答案

我不认为这只是未释放上下文的问题(上下文不会保持打开的事务 - 由于未提交的更改,您会看到它).如果您遇到此问题,您很可能不会在每个请求中使用新的上下文实例,或者您在共享上下文实例(= 一个连接)上有一些多线程/异步处理.这个异常表示多个线程(可能是多个处理的请求)试图在同一个连接上使用它们自己的事务——这是不可能的.

I don't think that this is only problem of not disposed contexts (context doesn't keep opened transaction - you would see it because of uncommitted changes). If you have this problem you most probably don't use the new context instance per request or you have some multi threaded / asynchronous processing on the shared context instance (= one connection). This exception says that multiple threads (probably multiple processed requests) are trying to use their own transaction on the same connection - that is not possible.

角落案例可以是手动处理提供给上下文的连接,但我想如果你使用它,你会提到它.

Corner case can be manual handling of connections provided to context but I guess you would mention it if you use it.

您的工厂不提供每个请求上下文 - 它为所有请求提供单一上下文!!!该静态字典在所有请求之间共享,因此第一个创建实例并将其存储在 _DEFAULT 键下,所有其他请求都将使用它.

Your factory doesn't provide per request context - it provides single context for all request!!! That static dictionary is shared among all request so the first creates instance and stores it under _DEFAULT key and all other requests will use it.

这篇关于不允许新事务,因为会话中还有其他线程在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆