nHibernate 会话和多线程 [英] nHibernate session and multithreading
问题描述
我有一个方法有很多使用 nHibernate 会话的持久性调用,它有效,没问题.但是由于多线程原因,我需要重构这个方法,从循环内的内容中提取一个方法.然后我用这个方法创建了一个类.就像是正常的重构,但是这个方法调用里面的nHibernate session坏了,没有上下文,我也没有任何时候敲定.nHibernate 在多线程方面有问题吗?即使我只有一个线程在执行,我也有同样的问题.
I had a method with a lot of persistence calls that used a nHibernate session, it worked, was alright. But I needed to refactor this method, extracting a method from a content inside a loop, for multithread reasons. Then I created an class with this method. It is like a normal refactoring, but the nHibernate session inside this method call is broken, without context, I didn't finalize it at any moment. Has nHibernate problems with multithreading? Even when I have only one more thread executing, I have the same problem.
我通过 SessionFactory 和 Façade 模式使用 nHibernate Session,这意味着,会话不是这些对象的字段,它在 SessionFactory 是全局的.
I use nHibernate Session through a SessionFactory and Façade pattern, it means, the session is not a field of these objects, it is global at SessionFactory.
说得更清楚一点:
之前:
Method()
{
... persistence calls
foreach(Thing..)
{
...persistence calls for each thing (1)
}
...
}
之后:
Method()
{
... persistence calls
foreach(Thing..)
{
create a thingResolver object with some data
open a new thread with thingResolver.Method (1)
starts this thread
}
.. waits for finishing threads and continues
}
<小时>
我们的 nHibernate 会话工厂是线程感知的,并且存储/检索每个线程的 nHibernate 会话.现在运行良好;)
Our nHibernate Session Factory is thread-aware, and stores/retrieves nHibernate session per thread. It is working nicely now ;)
推荐答案
会话在 NHibernate 中按设计不是线程安全的.所以只要你有一个会话只被一个线程使用就可以了.
Sessions are not thread safe in NHibernate by design. So it should be ok as long as you have a session used by only one thread.
我不确定你是 whatResolver 做了什么,但是如果它在你在原始线程中创建的同一个会话上做了一些持久性调用 - 这很可能是你问题的原因,你可以在你的新线程中创建一个单独的会话,这样如果我的假设是真的,它就会是每个线程的一个会话.
I'm not sure what you're thingResolver does, but if it does some persistance calls on the same session you've created in the originating thread - this most probably the cause of your problems, you could create a separate session in your new thread so that it would be a session per thread if my assumption is true.
NHibernate 参考在 10.2 节中有它
NHibernate reference has it in section 10.2
http://nhibernate.info/doc/nh/en/index.html#transactions
这篇关于nHibernate 会话和多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!