How long can/should an NHibernate session be kept open?

 ̄綄美尐妖づ 提交于 2019-12-23 12:58:10

问题


I've created a windows service which is listening to a MSMQ. For each message I receive, some DB transactions need to be made. Later it might be possible that there will be 1 message every second. Currently the Nhib session is kept open until the service is stopped manually. Is it a good practice or should I close the session after each message?

Thanks in advance


回答1:


An NHibernate session is meant to be relatively short lived, so its generally not a good idea to keep it active for a longer period. The session caches entities and as more entities are fetched more data is cached, if you don't manage the caching in some way. This leads to a performance degradation.

The NHibernate docs describe ISession like this:

A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps an ADO.NET connection. Factory for ITransaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.

I would suggest using a session-per-conversation, i.e. if you have a few db operations that "belong together" you use the same session for those operations, but when those operations are done you close the session.

So, using a new session for each message you process sounds like a good idea.




回答2:


In contrast to the session factory (ISessionFactory) which is thread safe you should open and close the session (ISession) with every database transaction.



来源:https://stackoverflow.com/questions/1243835/how-long-can-should-an-nhibernate-session-be-kept-open

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