Question

In my page consists of a repeater and bind some data using store procedure from SQL Server 2008.

rptTour.DataSource = GetData();
rptTour.DataBind();

Data binding GetData()

SqlCommand cmdSelectAllMatch = new SqlCommand("sp_sel_Tour", Global.conn);
    SqlDataReader dtrSelectAllMatch = null;
    Collection<TourBO> TourData = new Collection<TourBO>();

    try
    {
        Global.connD2W.Open(); //error here, line 23
        cmdSelectAllMatch.CommandType = System.Data.CommandType.StoredProcedure;
        dtrSelectAllMatch = cmdSelectAllMatch.ExecuteReader();

        while (dtrSelectAllMatch.Read())
        {
            TourBO Tour = new TourBO();
            TourID = Convert.ToInt16(dtrSelectAllMatch[dtrSelectAllMatch.GetOrdinal("ID")]);
            Tour.Name = dtrSelectAllMatch[dtrSelectAllMatch.GetOrdinal("Name")].ToString();


            TourData.Add(Tour);
        }
    }
    catch(Exception ex)
    {
        Global.Log(ex.ToString());
    }
    finally
    {
        Global.connD2W.Close();            
    }

    if (dtrSelectAllMatch != null)
    {
        dtrSelectAllMatch.Close();
    }
    return TourData;

This is the sqlconnection that will be share among the entire application.

public static SqlConnection connD2W = new SqlConnection(ConfigurationManager.ConnectionStrings["D2WConnectionString"].ConnectionString);

It just read through all the data from data reader and assign into a custom collection and pass back to the repeater.

Everything working fine when i test by myself. But when i run the Lost Test using Visual Studio (20 users and run for 2 minutes), i received errors below in my error log file(same error keep repeat)

Log Entry : 9:59:05 AM Thursday, November 07, 2013
:System.InvalidOperationException: The connection was not closed. The connection's current state is connecting.
at System.Data.ProviderBase.DbConnectionBusy.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at TourDAL.GetAllScheduledMatch() in c:\Documents\Visual Studio 2010\WebSites\test\App_Code\DAL\TourDAL.cs:line 23

Does it means this function not allowed multiple user to access it at the same time? Any way to solve this?

Was it helpful?

Solution

If you're using a global connection (e.g. defined as a global variable or a static variable), that won't work in an environment where you have multiple threads running at the same time (e.g. in a web server).

The reason for it is all threads will go through the same code. The first one will open the connection and it will stay open for all the others as well.

It's best to define a connection locally, open and close it as soon as the job is done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top