I want to rebuild multithread NHibernate application with session per request implementation.
Now this application looks like session per conversation (per thread) with saving session into the CurrentSessionContext.
But this implementation bring problems with loading cached entities, that can be already updated from other sessions. So I want to change this code
//main thread
using (nHibernateHelper.OpenConnection()){
List<Bar> bars = BarRepository.Instance.GetAll();
foreach (Bar bar in bars){
//start thread and do some work, for example run DoWork(bar); by other thread
Task.Factory.StartNew(DoWork, bar);
}
}
//other thread
void DoWork(Bar bar){
using (nHibernateHelper.OpenConnection()){
foreach (Foo foo in bar.FooList){
if (foo.SomeState == PredifinedState) {
//call many other functions
}
}
}
}
The main question is: How to change this code, to close Session before starting other thread with using LazyLoading (Bar contains relations to other objects and this relations are using during thread work), and before calling other functions from foreach statement in DoWork function?
In NHibernate, Sessions are explicitly not threadsafe (see http://nhibernate.info/doc/nh/en/index.html#transactions), so you can’t share them between multiple threads without locking.
Without more context to your problem it’s hard to provide an exact solution, but would something like the below be helpful?