0

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()?

Staly
  • 85
  • 7
  • Possible duplicate of [Queries and Commits take longer as the session lives on](http://stackoverflow.com/questions/43934112/queries-and-commits-take-longer-as-the-session-lives-on) – Frédéric May 15 '17 at 12:27

1 Answers1

1

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.

Community
  • 1
  • 1
Paul Hatcher
  • 7,342
  • 1
  • 54
  • 51
  • While you were writing it, I noticed that _session is swelled by elements that are in "Statistics" property. After each transaction I made _session.Clear() and it looks like it made my day, but I don't know if are there some strong consequences in using it. – Staly May 15 '17 at 12:03
  • There are already some discussion about this in the [post](/q/43934112/1178314) your question is a duplicate of. – Frédéric May 15 '17 at 12:29
  • I didn't find it while searching. I don't have any dependencies between transactions, so it looks like I can use it. Thanks for help, everyone. – Staly May 15 '17 at 12:52