views:

334

answers:

3

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

Does anyone have any tips for executing queries through NHibernate in a new asynchronous thread?

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

public void Page_Load()
{
    ThreadPool.QueueUserWorkItem(state => FooBarRepository.Save(new FooBar()));
}
+1  A: 

Sessions are not thread-safe. IOW you'll run into issues sooner or later if you create a session on one thread and use it from another. Create a new session on your background thread and close it before your background thread finishes.

John Rayner
A: 

How about:

public void Page_Load()
{
    ThreadPool.QueueUserWorkItem(state => NHibernateSessionFactory.GetSession().Save(new FooBar()));
}
reach4thelasers
This can cause memory/connetionpool leaks
Paco
+1  A: 
Trent