King Chan
King Chan

Reputation: 4302

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?

Upvotes: 1

Views: 4689

Answers (2)

Bryan Crosby
Bryan Crosby

Reputation: 6554

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.

Upvotes: 2

Ofer Zelig
Ofer Zelig

Reputation: 17490

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.

Upvotes: 2

Related Questions