Asynchronous requests in a web application using NHibernate

In a web application, a session is available only in the current thread.

Does anyone have any advice on making requests through NHibernate in a new asynchronous thread?

For example, how could I do something like this work:

public void Page_Load() { ThreadPool.QueueUserWorkItem(state => FooBarRepository.Save(new FooBar())); } 
+4
source share
3 answers

You must have a session context smart enough for a non-web context. But more importantly, the new thread must have its own session.

You can use something like the following:

 private ISession threadSession { get { if (HttpContext.Current != null) { return (ISession)HttpContext.Current.Items["THREAD_SESSION"]; } return (ISession)AppDomain.CurrentDomain .GetData("THREAD_SESSION" + Thread.CurrentThread.ManagedThreadId); } set { if (HttpContext.Current != null) { HttpContext.Current.Items["THREAD_SESSION"] = value; } else { AppDomain.CurrentDomain.SetData("THREAD_SESSION" +Thread.CurrentThread.ManagedThreadId, value); } } } 
+3
source

Sessions are not thread safe. IOW, sooner or later you will run into problems if you create a session in one thread and use it from another. Create a new session in the background thread and close it before the background thread ends.

+1
source

What about:

 public void Page_Load() { ThreadPool.QueueUserWorkItem(state => NHibernateSessionFactory.GetSession().Save(new FooBar())); } 
-one
source

All Articles