开发者

Does my .Net SqlConnection object close on its own

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开发者_如何学Go 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();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜