Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6737309
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T11:14:02+00:00 2026-05-26T11:14:02+00:00

I have a ASP.NET MVC application for which I want to write some stress

  • 0

I have a ASP.NET MVC application for which I want to write some stress tests in sense of concurrent database access from multiple threads. I wrote it as a unit test using Parallel.ForEach(), but was not able to make it work since I was getting the following exception most of the time:

There is already an open DataReader associated with this Command which must be closed first

So I simplified the test as much as possible and here it is

[Test]
public void Can_Access_DB_Concurrently()
{
    Parallel.ForEach(Enumerable.Range(0, 9), x =>
    {
        try
        {
            var sessionBuilder = new HybridSessionBuilder();             
            var session = sessionBuilder.GetSession();

             using (ITransaction transaction = session.BeginTransaction())
             {
                 var job = session.Query<Job>().Where(y => y.Name == "TestProject").SingleOrDefault().Name;
                 Trace.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Job name is " + job);
                 transaction.Commit();
             }                
        }
        catch (Exception e)
        {
            Trace.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Exception: " + e.Message);
        }
    });
}

Typical output:

13: Exception: Object reference not set to an instance of an object.
16: Exception: There is already an open DataReader associated with this Command which must be closed first.
9: Exception: There is already an open DataReader associated with this Command which must be closed first.
16: Exception: There is already an open DataReader associated with this Command which must be closed first.
14: Exception: There is already an open DataReader associated with this Command which must be closed first.

The HybridSessionBuilder looks like this:

public class HybridSessionBuilder : ISessionBuilder
{
    private static ISessionFactory _sessionFactory;
    private static ISession _currentSession;

    public ISession GetSession()
    {
        ISessionFactory factory = getSessionFactory();
        ISession session = getExistingOrNewSession(factory);
        return session;
    }

    private ISessionFactory getSessionFactory()
    {
        lock (this)
        {
            if (_sessionFactory == null)
            {
                Configuration configuration = GetConfiguration();
                _sessionFactory = configuration.BuildSessionFactory();
            }

            return _sessionFactory;
        }
    }

    public Configuration GetConfiguration()
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["StagingDatabase"].ConnectionString;

        Configuration configuration = new Configuration();
        configuration = PostgreSQLConfiguration.PostgreSQL82
              .ConnectionString(connectionString)
              .Dialect("NHibernate.Dialect.PostgreSQL82Dialect")
              .UseReflectionOptimizer()
              .AdoNetBatchSize(50)
              .ConfigureProperties(new Configuration());

        configuration.AddMappingsFromAssembly(typeof(Job).Assembly);
        Fluently.Configure(configuration);
        return configuration;
    }

    private ISession getExistingOrNewSession(ISessionFactory factory)
    {
        {
            if (HttpContext.Current != null)
            {
                ISession session = GetExistingWebSession();
                if (session == null)
                {
                    session = openSessionAndAddToContext(factory);
                }
                else if (!session.IsOpen)
                {
                    session = openSessionAndAddToContext(factory);
                }

                return session;
            }

            if (_currentSession == null)
            {
                _currentSession = factory.OpenSession();
            }
            else if (!_currentSession.IsOpen)
            {
                _currentSession = factory.OpenSession();
            }
        }

        return _currentSession;
    }        

    public ISession GetExistingWebSession()
    {
        return HttpContext.Current.Items[GetType().FullName] as ISession;
    }

    private ISession openSessionAndAddToContext(ISessionFactory factory)
    {
        ISession session = factory.OpenSession();
        HttpContext.Current.Items.Remove(GetType().FullName);
        HttpContext.Current.Items.Add(GetType().FullName, session);
        return session;
    }        
}

Apparently I am doing something wrong with this concurrent access, but I am unable to spot the error. Thank you for any advice.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T11:14:02+00:00Added an answer on May 26, 2026 at 11:14 am

    HybridSessionBuilder is storing the ISession in a static member and therefore reusing it for each thread. The simplest solution to fix your tests would be to remove the static keyword from _currentSession. Each instance of HybridSessionBuilder would then provide a different ISession.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an ASP.NET MVC-application which I want deployable on both IIS6 and IIS7
I have a Asp.net MVC 3 application which I want to give to a
I have a ASP.NET MVC application which is build up as an assembly that
I have an ASP.NET MVC 3 application which has a post action called Create
I have an .NET 4.0 ASP.NET MVC application, which also hosts a Workflow Foundation
I created a simple ASP.NET MVC version 1.0 application. I have a ProductController which
We have an ASP.NET application on ASP.NET 4.0 using MVC 3 which uses Windows
I have an ASP.NET MVC application which is executing a search against a products
I have a jQuery accordion in a page in ASP:Net MVC application in which
I have an ASP.NET MVC application where I am editing an existing database to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.