简体   繁体   中英

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. 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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