简体   繁体   中英

Having issue in connection string of already an open DataReader

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

I m facing this issue when same person open the same page at same time on different system. I have searched a lot on this but found no successful solution.

I have tired :

  1. MultipleActiveResultSets = true in connection string
  2. Increasing Connection waiting time
  3. Verified all connection are closed

This issue comes only when above condition created. Kindly let me know solution which really works

this my connection function which im using

public DataSet SelectDs(string str)
{
    DataSet ds = new DataSet();

    if (con.State == ConnectionState.Closed)
    {
        con.ConnectionString = ConStr;
        con.Open();
    }

    cmd.CommandText = str;
    cmd.Connection = con;
    cmd.CommandTimeout = 12000;
    adpt.SelectCommand = cmd;
    adpt.Fill(ds);

    con.Close();
    return ds;
}

It is a mortal sin to use a global connection object in that way. It is bad (very bad) in WinForms applications, but in ASP.NET is deadly. (as you have discovered)

The usage pattern for a disposable object (and an expensive one like the connection) is

CREATE, OPEN, USE, CLOSE, DESTROY

The Connection Pooling mechanism exist to make easier the usage of this pattern.
Instead you try to work against it and you pay the consequences.

Your code should be rewritten as

public DataSet SelectDs(string str)
{
    DataSet ds = new DataSet();

    using(SqlConnection con = new SqlConnection(constring))  // CREATE
    using(SqlCommand cmd = new SqlCommand(str, con))         // CREATE
    {
        con.Open();    // OPEN
        cmd.CommandTimeout = 12000;
        using(SqlAdapter adpt = new SqlAdapter(cmd))   // USE
             adpt.Fill(ds);

        return ds;
    }  // CLOSE & DESTROY 
}

How about putting inside a Using statement like

    using(SqlConnection connection = new SqlConnection("connection string"))
{

connection.Open();

using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
{
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        if (reader != null)
        {
            while (reader.Read())
            {
                //do something
            }
        }
    } // reader closed and disposed up here

   } // command disposed here

 } //connection closed and disposed here

in finally clause use this

if (readerObj.IsClosed == false)
{
  readerObj.Close();
}

I think you should also dispose your command object before returning dataset.

try cmd.Dispose() after con.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM