Skip to content

Instantly share code, notes, and snippets.

@josephvano
Last active December 18, 2015 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephvano/5766488 to your computer and use it in GitHub Desktop.
Save josephvano/5766488 to your computer and use it in GitHub Desktop.
NHibernate multiple sessions and stop leaking connections
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
ISession session1 = null;
ISession session2= null;
ITransaction tx1 = null;
ITransaction tx2 = null;
bool rollback = false;
try
{
session1 = factory1.OpenSession();
tx1 = session1.BeginTransaction();
session2 = factory2.OpenSession();
tx2 = session2.BeginTransaction();
//do work
tx1.Commit();
//throw exception
tx2.Commit(); //never hits
}
catch (Exception ex)
{
//Log it
_logger.Error("Something terrible has happened!", ex);
rollback = true;
if(tx1.IsActive && !tx1.WasCommitted && !tx1.WasRolledBack)
{
tx1.Rollback();
}
// KLUDGE: race condition? DTC?
Thread.Sleep(500);
// txt2.IsActive = Flase with thread.sleep()
if(tx2.IsActive && !tx2.WasCommitted && !tx2.WasRolledBack)
{
tx2.Rollback();
}
}
if(!rollback)
{
scope.Complete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment