简体   繁体   中英

Can an NHibernate session have two data readers open in separate threads?

I'd like to know the correct approach for running two simultaneous queries using NHibernate. Right now, I have a single ISession object that I use for all my queries:

session = sessionFactory.OpenSession();

In one thread, I'm loading some data which takes 10-15 seconds, but I don't need it right away so I don't want to block the entire program while it's loading:

IDbCommand cmd = session.Connection.CreateCommand();
cmd.CommandType = CommandType.TableDirect;
cmd.CommandText = "RecipesForModelingGraph";
IDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
   // Do stuff
}

reader.Close();

This works fine, however in another thread I might be running a query such as:

var newBlah = new Blah();
session.Save(newBlah);

When the above transaction commits, I occasionally get an exception:

Additional information: There is already an open DataReader associated with this Command which must be closed first.

Now, I thought maybe this was because I was running everything in the same transaction. So, I surrounded all my loading code with:

using (ITransaction transaction = session.BeginTransaction(IsolationLevel.Serializable))
{
   // Same DataReader code as above
}

However, the problem has not gone away. I'm thinking maybe I need each thread to have its own ISession object. Is this the correct approach, or am I doing something wrong. Note, I only want a single open connection to the database. Also, keep in mind the background thread is only loading data and nothing else, so I'm not worried about isolation levels and data changing as its being read.

The session is tied to the thread and the Commands created are linked to the sessions connection object. So yes, if a commit or close is executed while an open reader exists you will get an exception.

You could Join() your threads and wait until all are complete before closing/committing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM