Reputation: 2345
I'm in the process of creating a WPF application with a rich front end. The issue I was running with from the beginning is that the UI would lock up whenever the user would change their filters. I originally fixed the issue by querying the database using NHibernate in a BackgroundWorker
. It worked reasonably well for a short amount of time but NHibernate often throws various exceptions such as complaining that a session is already open.
How can I mix NHibernate session and threading in a WPF application?
I'm thinking that because I inject an open ISession
instance into my repository and use that repository in several different threads that maybe I'd be better off simply injecting ISessionFactory
instead and open a new session in my repository functions.
The scenario in which this BackgroundWorker
is being used is the user are able to select one of many roles. Every time a role is checked or unchecked I use my background worker to query the database. If you check two roles really fast then NHibernate throws an exception saying the session is already in use because because it's still trying to fetch the data for the first check action.
Essentially, it would be nice to detect that if NHIbernate is already running a query then to cancel it and start executing the new one. This would make sense because if a user selects 2 roles (thus, requiring 2 queries) then the first query is no longer valid.
Any ideas?
Upvotes: 0
Views: 572
Reputation: 13686
You need to make sure you have one session per thread. You can't spread sessions across multiple threads. When you kick off your background thread, create a new session. When you no longer need the thread, kill it and close the session.
Upvotes: 1