简体   繁体   English

当应用程序关闭时,DB连接会立即关闭吗?

[英]When application close, will DB connection close instantly?

This is something I has been always wonder.... will it? 这是我一直想知道的......会吗?

Because whenever I write code to use DB connection, I always somehow have to ensure is closed before process to next piece. 因为每当我编写代码来使用数据库连接时,我总会以某种方式确保在处理到下一个部分之前关闭。

But when if the I have a ChildWindow that open a connection in its constructor and not close it until it hits the Save Button or Cancel Button. 但是,当我有一个ChildWindow在其构造函数中打开一个连接而不是关闭它,直到它命中保存按钮或取消按钮。 Then if the whole Application got closed, will the DB connection close instantly? 然后,如果整个应用程序关闭,数据库连接会立即关闭吗? Or it has to wait for the timeout and will close automatically? 或者它必须等待超时并自动关闭?

EDIT: 编辑:

So I am trying to keep a live connection open for logging all errors on my application: 所以我试图保持一个实时连接打开以记录我的应用程序上的所有错误:

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);            

}

Because I don't like how I open connection everytime log a single error, so I want to keep connection open all the time. 因为我不喜欢每次打开连接时都记录一个错误,所以我想保持连接一直打开。 This is similar as the OP I was describe. 这与我描述的OP类似。 In this situration, it keeps connection open all the time. 在这种情况下,它始终保持连接打开。 But will the DB connection close instantly after it exits? 但是数据库连接在退出后会立即关闭吗?

Short and simple answer: always use your connection in a using statement: 简短回答:始终在using语句中使用您的连接:

using (var db = new Connection())
{
    ...
}

and then you won't have to worry - it will just close when it goes out of scope, be it end of method, exception, or application shut down. 然后你不必担心 - 它会在超出范围时关闭,无论是方法结束,异常还是应用程序关闭。

Because I don't like how I open connection everytime log a single error, so I want to keep connection open all the time. 因为我不喜欢每次打开连接时都记录一个错误,所以我想保持连接一直打开。

That's what connection pooling is for. 这就是连接池的用途。 Have you measured your performance or have you identified strong evidence that this is a problem? 您是否已经衡量了自己的表现,或者您是否确认了这是一个问题的有力证据?

Open and close the connection with a using block and let the connection pool do it's job. using块打开和关闭连接,让连接池完成它的工作。

If your process exits, your connection will be closed. 如果您的进程退出,您的连接将被关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM