[英]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.提交更改时,新行和 SqlConnection object 被传递给处理行更改或添加的方法。
The process runs 5 times out of 10 all ok.该过程在 10 次中运行 5 次,一切正常。 The SqlConnection is opened at the start of the loop and closed after the loop however sometimes it does indeed close during the loop.
SqlConnection 在循环开始时打开并在循环后关闭,但有时它确实在循环期间关闭。 The code is no calling close() at any point during the loop.
代码在循环期间的任何时候都不会调用 close() 。
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:
连接关闭的主要时间是:
using
statement)using
语句)Close()
Close()
CommandBehaviour.CloseConnection
behaviourCommandBehaviour.CloseConnection
行为执行命令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.如果您实际上遇到异常(可能是超时或死锁),在
using
块中弹跳(处理它),并且可能吞下异常,则第一种是很有可能的。
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;要进行调查,您可以订阅
StateChange
事件并在处理程序中添加断点; 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.
如果您使用超出此代码的 scope 的连接,请记得取消订阅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.