简体   繁体   中英

nHibernate multiple transactions are slowing down

previously I had 500 operations in one transaction lasting too long, so I had to change it for 500 transactions in foreach block.

I am checking the time of making each transaction (I use Stopwatch) and I noticed that every foreach loop (every new transaction) is a bit longer than previous one. It raised from ~80 milliseconds to ~400. My code:

foreach (var single in data)
{
    using (var tran = _session.BeginTransaction())
    {
       // operations with "single" usage - _session.Save() or _session.Update()
       //...
       tran.Commit();
    }
}

What am I doing wrong? Should I dispose, flush something after tran.Commit()?

Nhibernate tracks the state of each entities in the session, so each time around the loop more and more entities need to be checked.

Typically the answer to this is to create a new session for each transaction.

The issue here is that you then have 500 small transactions which is a "chatty" way of using an ORM and usually considered an anti-pattern.

From NHibernate 3.2 batching has been implmented internally and I suggest you see Batch Update in NHibernate for details.

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