0

I just wonder if I do:

Session["MyDbConnection"] = new SqlConnection("connectionString");
(Session["MyDbConnection"] as SqlConnection).Open();

I can also do this when I navigate to another page?:

(Session["MyDbConnection"] as SqlConnection).Close();
6
  • Why use session on Db Connection? You are potentially opening up with lots of concurrent open connection, which will blow your max connections very quickly. You are asking for memory leak in your application. Commented Dec 10, 2017 at 6:58
  • Are you using an IoC container? Commented Dec 10, 2017 at 7:06
  • @12seconds - I just thought if I could close the connection immediately it will also cancel the open connection and also kills the long running queries just in case to prevent table locking. Commented Dec 10, 2017 at 8:39
  • @mjwills - I dont have IoC container. Commented Dec 10, 2017 at 8:40
  • what if i put SqlCommand Object intead of the SqlConnection into the Session object then I call the cancelled property of command to cancel the long running query? Will that be safe? Commented Dec 10, 2017 at 8:45

1 Answer 1

1

I'm not sure if that's possible, but even if it is, it's a bad idea. SqlConnection is an IDisposable and should only ever be used as a local variable inside a using statement.
When disposed, it's closed automatically and the connection pool can be used.
Note the following paragraph from SQL Server Connection Pooling page on Microsoft docs:

Caution
We strongly recommend that you always close the connection when you are finished using it so that the connection will be returned to the pool. You can do this using either the Close or Dispose methods of the Connection object, or by opening all connections inside a using statement in C#, or a Using statement in Visual Basic. Connections that are not explicitly closed might not be added or returned to the pool.

The correct way to use SqlConnection is this:

using(var con = new SqlConnection(connectionString))
{
    using(var cmd = new SqlCommand(commandText, con)
    {
        // Add parameters if needed: 
        // cmd.Parameters.Add("name", SqlDbType.<some SqlDbType Member>).Value = <some value>
        // Execute your command here and do whatever you need with it.
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

will it instantly close the connection once the user navigates to other page? or it has to wait until the current request times out then the connection will be freed?
@ajgo I don't know. It's been a very long time since I last wrote an asp.net web application.
will it instantly close the connection once the user navigates to other page? No. Each web request is independent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.