C# 连接没有关闭,连接的当前状态是打开的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19089305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The connection was not closed, The connection's current state is open
提问by user2830395
I'm writing an ASP.NET application. In my datalayer an sql connection is being opened and closed before and after querying. The SqlConnection is being kept as a private field of a single class. Every database call in the class uses the same structure:
我正在编写一个 ASP.NET 应用程序。在我的数据层中,在查询前后打开和关闭了一个 sql 连接。SqlConnection 被保留为单个类的私有字段。类中的每个数据库调用都使用相同的结构:
conn.Open();
try
{
// database querying here
}
finally
{
conn.Close();
}
Yet, on very rare occasions I get the exception 'The connection was not closed. The connection's current state is open'. It's not possible to reproduce the problem since it originates very rarely from different parts of the code. There is some threading involved in my application but new threads also make new data layer classes and thus new connection objects.
然而,在极少数情况下,我会收到异常“连接未关闭”。连接的当前状态为“打开”。不可能重现该问题,因为它很少来自代码的不同部分。我的应用程序中涉及一些线程,但新线程也会创建新的数据层类,从而创建新的连接对象。
I do not understand how it's possible to have a connection lingering around open using the code above. Shouldn't the connection always be closed after opening, making it impossible for the above exception to occur?
我不明白如何使用上面的代码打开一个连接。连接打开后不应该一直关闭,导致上面的异常不可能发生吗?
采纳答案by DGibbs
It's likely that an exception is being thrown in the try
block that you aren't handling. See this note in MSDN for try-finally:
很可能在try
您未处理的块中抛出了异常。请参阅 MSDN 中的此注释以了解try-finally:
Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered.
在处理的异常中,保证运行关联的 finally 块。但是,如果异常未处理,finally 块的执行取决于如何触发异常展开操作。
I would recommend wrapping the connection in a using
block anyway:
using
无论如何,我建议将连接包装在一个块中:
using (SqlConnection connection = new SqlConnection(connectionString))
{
//etc...
}
Alternatively, add a catch block to the try-finally
:
或者,将 catch 块添加到try-finally
:
conn.Open();
try
{
}
catch
{
}
finally
{
conn.Close();
}
回答by Suraj Singh
you should close connections as soon as you operations finished. Try to open connections for the shortest time possible. However it is best to use usingit will call Dispose method even in case of exceptions.
您应该在操作完成后立即关闭连接。尝试在尽可能短的时间内打开连接。但是最好使用使用它即使在异常情况下也会调用 Dispose 方法。
using (SqlConnection conn= new SqlConnection(conStr))
{
//etc...
}
OR
或者
1)Open the connection
1)打开连接
2)Access the database
2)访问数据库
3)Close the connection
3)关闭连接
//conn.Open();
try
{
conn.Open();
//Your Code
}
finally
{
conn.Close();
conn.Dispose();//Do not call this if you want to reuse the connection
}