Spring.Net / NHibernate - Multi Threading

621 views Asked by At

I'm using Spring .Net and Fluent NHibernate in my window application, and I'm working with multiple threads. I read in some blogs and questions that there can only be one session per thread, and I'm using the HibernateDaoSupport and CurrentSession to do it:

   public class DaoBase<T> : HibernateDaoSupport, IDaoBase<T>
    {
        protected ISession CurrentSession
        {
            get { return SessionFactoryUtils.GetSession(HibernateTemplate.SessionFactory, true); }
        }
}

However, I am testing this feature and must show that the sessions of each thread are different sessions. How can I do it?

Obs: After some research I found that objects obtained through a nhibernate session, can not be changed in another session, for example, can not find an object in the "Session 1" and give an update on the same object in "Session 2". But, in my tests I'm getting an object with the first thread and updating the same in the second thread, this is working. Whats are wrong?

1

There are 1 answers

0
Oskar Berggren On

You've got it backwards - a thread can have how many NHibernate sessions it likes. The important thing is that the session is not designed to be threadsafe, so only one thread at a time can operate on a particular session.

Until a session has been disposed, operating on an object loaded from that session also counts as "working with the session", since it may trigger lazy loads etc. So objects loaded from a still-active session should normally only be accessed from a single thread at a time.

As with any violation of thread-safety rules, there is no guarantee that it will break. But there is no promise that it will work either.

Your Test You can have each thread access CurrentSession, and put the instance in some shared collection, where the test runner thread can then access the collection of sessions and verify that all elements in the collection are distinct instances.