That can be a moronic question

There is a program on c # there is a query to mySql already approximately like this:

while (!(Connect.State == System.Data.ConnectionState.Open)) { Connect.Open(); } MySqlCommand command = new MySqlCommand(sqlQuery, Connect); return command.ExecuteReader(); 

That is the question

When requesting to get 50 lines, it gives an error (I understand that it is not correct, but each request is a separate command, it is simply called in the class constructor, when the array is filled)

 Connection must be valid and open. 

Well, that's actually the question of what could be wrong.

  • although in another class (also a subsidiary of the same parent) and one hundred normally filled in, the constructor uses the parent - Anton Kartushin
  • You keep somewhere an open reader that uses the same connection - Igor
  • Does it actually lie: 1) another error on the reader 2) a new connection is created for each call. And the strangest mistake, that is, no. Ie not every time appears, but after one or two passes (all passes are identical, I mean, I produce the same actions) - Anton Kartushin
  • You +1 for vryat. - Igor
  • Show a minimal example to reproduce the problem. Pokp it seems that you somehow somehow incorrectly work with the connection. And the loop with Open looks like some kind of hack. - PashaPash ♦

1 answer 1

Thank you guys for your attention! I figured it out. The bottom line is that the Garbage Collector did not have time to Destroy all the connections, and therefore I got an error. Too many connections rewrote the methods of interacting with the connection.

  • The garbage collector and should not deal with closing connections. MySqlConnection - IDisposable, you need to either wrap it in using, or call Close / Dispose by hand. And what, that when garbage collection connection is closed - this is protection in case of very very misuse. - PashaPash ♦
  • one
    Read about connection pools in ADO.NET, the deterministic release of unmanaged resources (the connection is just this), the IDisposable interface and the using statement. The above said is true: the fact that Dispose is called in the finalizer (this is how the GC “closes” the connections) is a side effect, moreover, since the finalizer is called (if IDisposable is correctly implemented, its call is most often canceled), the object experiences one garbage collection , and is removed only during the second pass of the collector. It is not good. - Serafim Prozorov