这是我一直想知道的事情......会吗?
因为每当我编写代码来使用数据库连接时,我总是必须以某种方式确保在处理下一个片段之前关闭。
但是,如果我有一个 ChildWindow,它在其构造函数中打开一个连接,并且在它点击保存按钮或取消按钮之前不会关闭它。那么如果整个应用程序关闭,数据库连接会立即关闭吗?还是要等到超时后自动关闭?
编辑:
所以我试图保持实时连接打开以记录我的应用程序中的所有错误:
public App()
{
ErrorHelper errorHelper = new ErrorHelper(); // Will open DB connection
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);
}
/// <summary>
/// For catch all exception and put them into log
/// </summary>
void currentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
errorHelper.WriteError(e.ExceptionObject as Exception);
}
因为我不喜欢每次都记录一个错误时打开连接的方式,所以我想一直保持连接打开。这与我所描述的 OP 类似。在这种情况下,它始终保持连接打开。但是DB连接退出后会立即关闭吗?
最佳答案
简短的回答:始终在 using
语句中使用您的连接:
using (var db = new Connection())
{
...
}
然后您就不必担心 - 它会在超出范围时关闭,无论是方法结束、异常还是应用程序关闭。
关于c# - 当应用程序关闭时,数据库连接会立即关闭吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9811755/