Does my .Net SqlConnection object close on its own

一笑奈何 提交于 2019-12-25 06:31:15

问题


We have a simple loop process that does some stuff on some datarows.

When commiting changes the new row and a SqlConnection object are passed to a method that handles the row change or addition.

The process runs 5 times out of 10 all ok. The SqlConnection is opened at the start of the loop and closed after the loop however sometimes it does indeed close during the loop. The code is no calling close() at any point during the loop.

So my questions is why it might close on it's own.

Cheers

For a reference the code resembles the following

connection.Open();

foreach(DataRow row in rows)
{
  if(rubbish)
{
   //make some changes and save
   DatabaseConnector.Save(sqlStringToExecute, connection);
}
}

connection.Close();

回答1:


A connection will not close on its own, no. The main times a connection would close would be:

  • disposal (for example via a using statement)
  • explicit call to Close()
  • a command is executed with the CommandBehaviour.CloseConnection behaviour
  • garbage collection - kind-of (although this is a bit different, really)
  • the server ceases to be available

The first is very possible if you are actually getting an exception (maybe timeout or deadlock), bouncing through the using block (disposing it), and perhaps swallowing the exception.

The third is very possible in well-meaning code.

To investigate, you could subscribe to the StateChange event and add a break-point in the handler; then walk backwards through the stack trace and you'll know exactly who is closing it, and why. If you use the connection beyond the scope of this code, remember to unsubscribe too.



来源:https://stackoverflow.com/questions/6121622/does-my-net-sqlconnection-object-close-on-its-own

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!