1

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

Replace

using (MySqlDataReader SqlDR = command.ExecuteReader())

with

using (MySqlDataReader SqlDR = command.EndExecuteReader()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.