Ayende @ Rahien

Unnatural acts on source code

NH Prof New Feature: Detect Cross Thread Session Usage

NHibernate sessions are not thread safe, and attempting to use them in multiple threads requires careful synchronization. It is generally better to consider a session only useful within the thread that created it.

There are valid scenarios for cross thread session usage (background loading with careful sync, multi request spanning session), but the invalid scenarios are far more common.

Let us take a look at the following code:

public class CrossThreadSession : IScenario
{
	public void Execute(ISessionFactory factory)
	{
		using(var session = factory.OpenSession())
		{
			var @event = new ManualResetEvent(false);

			ThreadPool.QueueUserWorkItem(state =>
			{
				using(var tx = session.BeginTransaction())
				{
					session.Get<Blog>(1);

					tx.Commit();
				}

				@event.Set();
			});

			@event.WaitOne();
		}
	}
}

If you’ll try to execute it with NH Prof listening, you are going to see this:

image

NH Prof is properly detecting and warning that we are using a single session in multiple threads.

I did mention that there are valid scenarios for that, so you can either just tell NHibernate to ignore this specific alert by clicking the link, or disable this alert completely if you are doing cross thread session usage extensively and you know it to be safe:

image

Nice enough feature, for about 30 minutes of work. I love working on NH Prof code base.

And just for fun, here is the test for this:

public class DetectCrossThreadSessionUsage : IntegrationTestBase
{
	[Fact]
	public void CanDetectCrossThreadSessionUsage()
	{
		ExecuteScenarioInDifferentAppDomain<CrossThreadSession>();

		var first = model.Sessions.First();

		Assert.Equal(1, first.Statistics.NumberOfStatements);
		Assert.Equal(2, first.Statistics.NumberOfTransactionsStatements);
		foreach (var statement in first.StatementsModel.Statements)
		{
			Assert.True(
				statement.Alerts.Any(alert => alert.HelpTopic == "CrossThreadSessionUsage"));
		}
	}
}

And for additional fun, here is the code to implement the feature:

public class CrossThreadSessionUsage : AbstractStatementProcessor
{
	public override void AfterAttachingToSession(SessionInformation session, TransactionStatement transaction)
	{
		AfterAttachingToSession(session, (SqlStatement)transaction);
	}

	public override void AfterAttachingToSession(SessionInformation sessionInformation, SqlStatement statement)
	{
		if (sessionInformation.SessionId.IdentifierId.ThreadId ==
			statement.SessionId.IdentifierId.ThreadId)
			return;
		statement.AcceptAlert(AlertInformation.CrossThreadSessionUsage());
	}
}

I did have to change some of the innards so NH Prof will track both the session id and the thread id, but that was quite easy to do and the only thing that actually took any time at all.

Comments

Anthony Dewhirst
08/05/2009 10:03 AM by
Anthony Dewhirst

Does NHProf update itself or do I need to get the latest version? How will I know when new geatures are added?

I have a license and wondered about this before.

Thanks for all the effort on this, its help my NH understanding loads

Anthony

Diego Mijelshon
08/05/2009 03:21 PM by
Diego Mijelshon

Just a style question (I'm curious)...

Why do you do this:

if (sessionInformation.SessionId.IdentifierId.ThreadId ==

statement.SessionId.IdentifierId.ThreadId)

return;

statement.AcceptAlert(AlertInformation.CrossThreadSessionUsage());

instead of:

if (sessionInformation.SessionId.IdentifierId.ThreadId !=

statement.SessionId.IdentifierId.ThreadId)

statement.AcceptAlert(AlertInformation.CrossThreadSessionUsage());
Ayende Rahien
08/05/2009 03:28 PM by
Ayende Rahien

Diego,

I prefer using exit conditions rather than conditional

Olav
09/28/2009 12:48 PM by
Olav

Makes sense once you have to test for more conditions and don't want lots of complex nested if's..

Comments have been closed on this topic.