How to keep single SQL Server connection instance open for multiple request in C#?

后端 未结 2 756
渐次进展
渐次进展 2020-12-22 13:27

I have a Web API which contains database insert logic (ado.net) in C#. When multiple users (e.g. 100 users) call the Web API, every time a SQL Server connection is opened an

相关标签:
2条回答
  • 2020-12-22 14:06

    ADO.NET's SqlConnection is implementing a connection pool. This means that when you close or dispose an instance of SqlConnection, the underlying connection simply returns to the pool. When another instance of SqlConnection is opened, and a connection is available in the connection pool, that connection will be used.
    In fact, Microsoft docs page on SQL Server Connection Pooling clearly states:

    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. For more information, see using Statement or How to: Dispose of a System Resource for Visual Basic.

    This means that the best practice way of using SqlConnection is this:

    using(var con = new SqlConnection(connectionString))
    {
        // your sql stuff goes here...
    }
    

    BTW, SqlCommand, SqlDataReader and SqlDataAdapter also implements the IDisposable interface, so they too needs to be used in the context of the using statement:

    using(var con = new SqlConnection(connectionString))
    {
        using(var cmd = new SqlCommand(sql, con))
        {
            // prepare command here - parameters and stuff like that
    
            // either
            using(var reader = cmd.ExecuteReader())
            {
    
            }
    
            // or 
            using(var adapter = new SqlDataAdapter(cmd))
            {
    
            }
    
        }
    }
    
    0 讨论(0)
  • 2020-12-22 14:15

    Well it's easy you just have to keep the connection open and if any readers opened they are closed.

    var con = new SqlConnection("Your connection String");
       con.open();
       //your code
    con.close()//after you have done your executions
    

    Have you tried Linq. It does the same thing you want, it keeps the connection alive and i think it'll be easier for you

    0 讨论(0)
提交回复
热议问题