You mentioned tracking potential memory leaks and the word “connection”. I am going to suggest that you mean a database connection.
You should ALWAYS wrap all your connections and commands into using . This ensures that the connection / command is deleted correctly, regardless of whether an error occurred, disconnecting the client, etc.
There are many examples here, but it comes down to something like:
using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand cmd = new SqlCommand(conn)) {
If for some reason your code does not allow you to do it this way, then I suggest the next thing you do is restructure it, as you did it wrong. A common problem is that some people will create a connection object at the top of the page and then reuse it for the life of the page. This is guaranteed to lead to problems, including but not limited to: errors in the connection pool, memory loss, random requests, complete removal of the application ...
Don't worry about performance when establishing (and dropping) connections where you need them in your code. Windows uses a connection pool, which is lightning fast and will support connections for as long as necessary, even if your application signals about it.
Also note: you must use this template EVERY TIME using an unmanaged class. They always implement IDisposable .
Notme
source share