0

I just started a new job and I'm dealing with a lot of code for websites that I did not write.

This error keeps happening in one of the websites but not all the time, sometimes the website works just fine and goes down for a few minutes or sometimes it goes down for hours:

ExecuteReader requires an open and available Connection. The connection's current state is open.

I have been checking and in all functions there is a function call Abrir() and Cerrar():

    private void Abrir(){
        try
        {
            conexion.Open();

        }
        catch (InvalidOperationException)
        {
            Cerrar();
        }
        catch (DbException)
        {
            throw new AccesoDatosExcepcion("No se pudo abrir la conexion con la BD");
        }
    }

    private void Cerrar()
    {
        try
        {
            conexion.Close();
        }
        catch (DbException)
        {
            throw new AccesoDatosExcepcion("No se pudo cerrar la conexion con la BD");
        }
    }

These functions are everywhere you need to open or close the connection so I don't know why it tells me I need an open connection.

Thanks for the help.

JuanR
  • 7,405
  • 1
  • 19
  • 30
  • Where does the error happen exactly? – ekad Jan 03 '18 at 14:38
  • I Would suggest you to put loggers and check rather than guessing. – Hameed Syed Jan 03 '18 at 14:39
  • 1
    You are posting the error but no stack trace. Either way, this is fairly common in applications that share database connections (like the pattern you have provided). The error is telling you that you are trying to do something with an existing connection and it is in an invalid state. I would recommend changing the code to create a new connection every time it needs one if at all possible. ADO.NET does pool management under the covers for you anyways. – JuanR Jan 03 '18 at 14:44
  • 3
    That's a terrible way to handle opening and closing connections, too easy to get out of sync and not properly dispose/close it. Wherever the problem is, it is not really in the code you shown. Something is leaking. – Crowcoder Jan 03 '18 at 14:44
  • 2
    Possible duplicate of [ExecuteReader requires an open and available Connection. The connection's current state is Connecting](https://stackoverflow.com/questions/9705637/executereader-requires-an-open-and-available-connection-the-connections-curren) – mnieto Jan 03 '18 at 14:45
  • 1
    you are trying to reuse a connection. Yes, the error message is confusing. The executeReader needs an avialable connection. If the connection is being used by another reader, the new one, throws this exception – mnieto Jan 03 '18 at 14:49

0 Answers0