我的 .Net SqlConnection 对象是否自行关闭 [英] Does my .Net SqlConnection object close on its own

查看:43
本文介绍了我的 .Net SqlConnection 对象是否自行关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个简单的循环过程,可以在一些数据行上做一些事情.

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

提交更改时,新行和 SqlConnection 对象将传递给处理行更改或添加的方法.

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

该过程运行了 10 次中的 5 次,一切正常.SqlConnection 在循环开始时打开并在循环后关闭,但有时它确实在循环期间关闭.代码在循环过程中的任何时候都没有调用 close().

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.

干杯

代码如下所示

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:

  • 处置(例如通过using语句)
  • 显式调用 Close()
  • 使用 CommandBehaviour.CloseConnection 行为执行命令
  • 垃圾收集 - 有点像(虽然这有点不同,真的)
  • 服务器不再可用

如果您确实遇到异常(可能是超时或死锁),在 using 块中弹跳(处理它),并且可能吞下异常,则第一个是很有可能的.

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.

要进行调查,您可以订阅 StateChange 事件并在处理程序中添加断点;然后通过堆栈跟踪向后走,你会确切地知道谁在关闭它,以及为什么.如果您使用超出此代码范围的连接,也请记得取消订阅.

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.

这篇关于我的 .Net SqlConnection 对象是否自行关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆