Improving database/system performance: Connection.Close() vs Connection.Dispose

AID: 3949
  • Status: Published

1800 points

  • Bynaman_goel
  • TypeTips/Tricks
  • Posted on2010-10-21 at 03:49:58
We are always hearing that we should dispose of a database connection rather than just closing it because a database connection is an unmanaged resource (SqlConnection, OledbConnection, OdbcConnection). So you would think the following code makes sense:

using(SqlConnection con= new SqlConnection())
{
//open database conncetion
//do database transaction
//close connection
con.Close();
}
                                    
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window



At first glance it looks like nice, clean code. We are closing all the resources we are opening as well as disposing (the using block will make sure that Dispose will be called for con object) the same to make sure there will be no memory leaks.

But when we go inside SqlConnection.Dispose() method using reflector, we find that we are again calling the same Close() method.
protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window




Dispose is doing much more than simply closing the connection,  – like making _poolGroup null. So the better approach to managing connections is:
using(SqlConnection con= new SqlConnection())
{
//open database conncetion
//do database transaction
//close connection
}
                                    
1:
2:
3:
4:
5:
6:

Select allOpen in new window



Now the Dispose() method will make sure that connection will be closed.

In addition, if we are simply calling con.Close(), as Close() we will leave the connection to the connection pool which will result in better performance. And then we can use Dispose() to remove the connection from the pool.

Following is the proper implementation of CloseConnection() which is called by the Close() method:
internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
{
    Bid.PoolerTrace("<prov.DbConnectionInternal.CloseConnection|RES|CPOOL> %d# Closing.\n", this.ObjectID);
    if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this))
    {
        try
        {
            DbConnectionPool pool = this.Pool;
            Transaction enlistedTransaction = this.EnlistedTransaction;
            if ((null != enlistedTransaction) && (enlistedTransaction.TransactionInformation.Status != TransactionStatus.Active))
            {
                this.DetachTransaction(enlistedTransaction);
            }
            if (pool != null)
            {
                pool.PutObject(this, owningObject);
            }
            else
            {
                this.Deactivate();
                this.PerformanceCounters.HardDisconnectsPerSecond.Increment();
                this._owningObject.Target = null;
                if (this.IsTransactionRoot)
                {
                    this.SetInStasis();
                }
                else
                {
                    this.PerformanceCounters.NumberOfNonPooledConnections.Decrement();
                    if (base.GetType() != typeof(SqlInternalConnectionSmi))
                    {
                        this.Dispose();
                    }
                }
            }
        }
        finally
        {
            connectionFactory.SetInnerConnectionEvent(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
        }
    }
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:

Select allOpen in new window



So my take on this is: If performance is not an issue, you can still use Connection.Dispose(). But if you want better performance use the Connection.Close() method I have described.
Asked On
2010-10-21 at 03:49:58ID3949
Tags

Connections. Close vs Dispose

,

sql

,

database

Topic

.NET

Views
1223

Comments

Author Comment

by: naman_goel on 2010-10-21 at 08:27:32ID: 20685

Thanks for editing this.

I looks fine to me.

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top .NET Programming Experts

  1. CodeCruiser

    588,856

    Sage

    6,000 points yesterday

    Profile
    Rank: Genius
  2. kaufmed

    377,702

    Wizard

    10 points yesterday

    Profile
    Rank: Genius
  3. BuggyCoder

    268,007

    Guru

    1,600 points yesterday

    Profile
    Rank: Sage
  4. TheLearnedOne

    232,552

    Guru

    4,900 points yesterday

    Profile
    Rank: Savant
  5. Idle_Mind

    193,005

    Guru

    0 points yesterday

    Profile
    Rank: Savant
  6. JamesBurger

    156,812

    Guru

    2,000 points yesterday

    Profile
    Rank: Sage
  7. wdosanjos

    124,308

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  8. Dhaest

    115,720

    Master

    0 points yesterday

    Profile
    Rank: Genius
  9. sedgwick

    112,918

    Master

    1,600 points yesterday

    Profile
    Rank: Genius
  10. nepaluz

    101,325

    Master

    0 points yesterday

    Profile
    Rank: Sage
  11. MlandaT

    95,921

    Master

    2,100 points yesterday

    Profile
    Rank: Genius
  12. navneethegde

    74,442

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  13. Masteraco

    70,367

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  14. binaryevo

    70,365

    Master

    0 points yesterday

    Profile
    Rank: Guru
  15. ambience

    69,104

    Master

    0 points yesterday

    Profile
    Rank: Sage
  16. emoreau

    68,230

    Master

    0 points yesterday

    Profile
    Rank: Genius
  17. PaulHews

    49,486

    0 points yesterday

    Profile
    Rank: Genius
  18. AndyAinscow

    45,290

    0 points yesterday

    Profile
    Rank: Genius
  19. Chinmay_Patel

    43,411

    0 points yesterday

    Profile
    Rank: Genius
  20. ged325

    41,700

    2,600 points yesterday

    Profile
    Rank: Genius
  21. RolandDeschain

    41,317

    0 points yesterday

    Profile
    Rank: Sage
  22. nishantcomp2512

    39,486

    0 points yesterday

    Profile
    Rank: Wizard
  23. tommyBoy

    36,550

    0 points yesterday

    Profile
    Rank: Genius
  24. mroonal

    35,000

    0 points yesterday

    Profile
    Rank: Sage
  25. santhimurthyd

    34,650

    0 points yesterday

    Profile
    Rank: Wizard

Hall Of Fame