2011-03-29 72 views
1

我有一段代碼來執行的MySqlCommand但有時拋出異常關閉MySQL的/ C#錯誤:已經有與此連接相關聯的打開的DataReader必須首先

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

這是不可預測的時有時候我的程序可以正常工作超過15分鐘,但是會發生異常。我在網上尋找答案,但我沒有找到任何東西。 這是我的代碼:

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; 
     } 

有一些沒有在評論工作的解決方案。 這是taht連接到mysql所以唯一的代碼,我相信所有的連接都關閉

回答

3

如果上面的代碼是您的本意,則不需要此行:

command.BeginExecuteReader(); 

SqlCommand.BeginExecuteReader方法:

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

+0

Thx!它現在完美了!我愚蠢的錯誤! – denBelg 2011-03-30 06:37:11

0

更換

using (MySqlDataReader SqlDR = command.ExecuteReader()) 

using (MySqlDataReader SqlDR = command.EndExecuteReader() 
相關問題