When application close, will DB connection close instantly?

杀马特。学长 韩版系。学妹 提交于 2019-12-23 02:09:23

问题


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. 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. In this situration, it keeps connection open all the time. But will the DB connection close instantly after it exits?


回答1:


Short and simple answer: always use your connection in a using statement:

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.




回答2:


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.

If your process exits, your connection will be closed.



来源:https://stackoverflow.com/questions/9811755/when-application-close-will-db-connection-close-instantly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!