Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design Patterns for SqlConnection, connection pooling and unit of works

It is clear that SqlConnections are pooled, so the using keyword seems perfect and this is the approach I always used and seen used.

For example...

public List<string> MyQuery()
{
    List<string> list = new List<string>();
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        // do some stuff with connection, process the resultset and fill the list.
    }
    return list;
}

The question is : with several queries for a webpage, is better to create the connection each time or to share the connection between queries, sharing it for an unit of work?

The performances will be much greater or is just a premature unnecessary microoptimization?

Is really important to close every connection as soon as possible or is better to try to pack the queries all together in an unit of work?

An example of an unit of work could be for example...

List<string> list1, list2;
string myvalue1, string myvalue2;

using (SqlConnection conn = new SqlConnection(connection))
{
    list1 = MyQuery1(conn);
    list2 = MyQuery2(conn);
    myvalue1 = MyQuery3(conn);
    myvalue2 = MyQuery4(conn);
}

This can happens during page load where multiple data should be get from database.

like image 948
Salvatore Previti Avatar asked Nov 07 '25 14:11

Salvatore Previti


1 Answers

Note that with connection pooling, you actually are not creating new connections with each 'new'... you are generally just getting one back from the pool.

Therefore, you should always open connections as late as you can, and close them as early as you can.

If a set of commands needs to be part of one transaction, then it needs to be done together. But beyond that, I think you should always close when you are done, and get a new one.

Even if you have no other code running between those commands... what if a thread context switch happens in between? Your connection object is needlessly open, doing nothing, waiting to get control back.

If you had closed it, it could have gone back to the pool.

like image 175
Andrew Barber Avatar answered Nov 09 '25 05:11

Andrew Barber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!