denBelg
denBelg

Reputation: 343

Mysql/C# error: There is already an open DataReader associated with this Connection which must be closed first

I have a piece of code to execute a mysqlcommand but sometimes it throws the exception

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

It is unpredictable when the exception will be throw sometimes my program works fine for over 15min but then it craches. I looked online for an answer but i didn't find anything. This is my code:

 public static List<string> DoCommand(string commandLine, string myConString) {
             MySqlCommand command = new MySqlCommand(commandLine);
            List<string> tables = new List<string>();
            try {
                using (MySqlConnection mySqlConnection = new MySqlConnection(myConString)) {
                    mySqlConnection.Open();
                    command.Connection = mySqlConnection;
                    command.BeginExecuteReader();
                    using (MySqlDataReader SqlDR = command.ExecuteReader()) {
                        while (SqlDR.Read()) {  //Async reading, wait untill reading is done
                            tables.Add(SqlDR.GetString(0));
                        }
                        //SqlDR.Close();
                        //SqlDR.Dispose();
                    }
                    //mySqlConnection.Close();
                    //mySqlConnection.Dispose();
                }
            } catch (Exception exp) { } finally {
                command.Connection = null;
            }
            //System.Threading.Thread.Sleep(50);     //Give connection time to flush
            return tables;
        }

there are some of the solutions that didn't work in comment. This is the only code taht connects to mysql so i am sure all connections are closed

Upvotes: 1

Views: 2541

Answers (2)

cdel
cdel

Reputation: 706

Replace

using (MySqlDataReader SqlDR = command.ExecuteReader())

with

using (MySqlDataReader SqlDR = command.EndExecuteReader()

Upvotes: 0

Mitch Wheat
Mitch Wheat

Reputation: 300559

If you above code is what you intended, this line is not required:

  command.BeginExecuteReader(); 

The SqlCommand.BeginExecuteReader Method:

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, and retrieves one or more result sets from the server

Upvotes: 3

Related Questions