nHibernate session and multithreading

与世无争的帅哥 提交于 2019-11-27 03:19:58

问题


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.

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.


Making it a little bit more clear:

BEFORE:

Method()
{
... persistence calls
foreach(Thing..)
{
...persistence calls for each thing (1)
}
...
}

AFTER:

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
}

Our nHibernate Session Factory is thread-aware, and stores/retrieves nHibernate session per thread. It is working nicely now ;)


回答1:


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.

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 reference has it in section 10.2

http://nhibernate.info/doc/nh/en/index.html#transactions




回答2:


You can have one NHibernate SessionFactory for multiple threads as long as you have a separate NHibernate session for each thread.

here is an example that will give exceptions because it uses the same session for each thread:

https://forum.hibernate.org/viewtopic.php?p=2373236&sid=db537baa5a57e3968abdda5cceec2a24

The solution is to store sessions on the LocaldataStoreSlot, that way you can have a session-per-request model.



来源:https://stackoverflow.com/questions/242961/nhibernate-session-and-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!