0
connection = CreateDBConnetion();
try 
{
    _ = ExecuteQuery(connection, query);

    OtherProcess();
}
catch (Exception ex)
{
    // Error
    // DB update opertions
}
finally
{
    connection.close()
    // Others
}

In the above code when some error occurred in otherProcess method and DB connection is still being used by ExecuteQuery method then while closing connection In finally block not working properly and also not throwing any exception. Not moving forward from from connection.close() and still ExecuteQuery method running in the background.

Any idea why it's not allowing me to closed connection while it's being used by some other process.

Jay Dadhaniya
  • 171
  • 4
  • 15
  • Don't create it at class level. Create the db connection _in the method_ and dispose it there also. Also read up on `using` rather than `Close`. – mjwills Feb 01 '21 at 10:39
  • Does this answer your question? [C# Data Connections Best Practice?](https://stackoverflow.com/questions/17552829/c-sharp-data-connections-best-practice) – Charlieface Feb 01 '21 at 10:46
  • I know that we should use `using` for batter practice but actually, I need DB connection in catch block also for DB update if any error occurred. I will update in my example code block. – Jay Dadhaniya Feb 01 '21 at 10:51
  • Put the `try catch` _inside_ the `using`. – mjwills Feb 01 '21 at 12:18
  • Already tried it but still not able to close the connection when it's being used somewhere else – Jay Dadhaniya Feb 04 '21 at 12:36

0 Answers0