When the application closes, will the DB connection occur immediately?

This is what I always asked myself a question ... isn't it?

Because whenever I write code to use a database connection, I always somehow have to be closed before the process to the next part.

But if I have a ChildWindow that opens a connection in its constructor and does not close it until it clicks the "Save" or "Cancel" button. Then, if the entire application is closed, will the DB connection occur immediately? Or should he wait for a timeout and will automatically close?

EDIT:

So, I am trying to keep an open connection open to log all errors in 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 the way I open the connection every time, logging one error, so I want to constantly open the connection. This is similar to the OP that I described. In this application, he constantly maintains a connection. But will there be a DB connection immediately after it leaves?

+1
source share
2 answers

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

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

and then you don’t have to worry - it just closes when it goes out of scope, whether the end of the method, exception or application ends.

+2
source

Because I don’t like the way I open the connection every time, logging one error, so I want to constantly open the connection.

What is the connection pool for? Have you measured your effectiveness or are you convinced that this is a problem?

Open and close the connection to the using block, and let the connection pool do this.

If your process is completed, your connection will be closed.

+2
source

All Articles