Solved

When to close my datareader

Posted on 2008-10-24
7
1,103 Views
Last Modified: 2013-12-17
I have inherited a C# webproject that has all of the data access code (calls stored procedures) in class files. I have added the different calls it makes below.  THis model is working fine. but now I want to try and use the data access classes with the Telerik RadGrid which I can bind using the OpenDataSource object, but it says I need to close the connection object and use the datareader.close() command.  I want to be sure I don't leave anything open which might use up memory, etc...What should I modify so that the openDataSource object can be used?
Thanks

For example it does this:
SQLDataReader sdrRole = null;
try
{
sdrRole = dbRole.GetRoleDetail(param1, param2, etc)
}
finally
{
if (sdrRole != null)
{
if (!sdrRole.IsClosed)
sdrRole.Close();
sdrRole = null;
}
}

Code in the class file:
       public SqlDataReader GetRoleDetail(int byUserID, int roleID)
        {
            SqlCommand cmd = new SqlCommand();

            try
            {
                // Set command statement
                cmd.CommandText = "spSelectRoleDetail";
                cmd.CommandType = CommandType.StoredProcedure;

                // Add parameters
                cmd.Parameters.Add(_db.MakeParam("@by_user_id", SqlDbType.Int, ParameterDirection.Input, 0, byUserID));
                cmd.Parameters.Add(_db.MakeParam("@role_id", SqlDbType.Int, ParameterDirection.Input, 0, roleID));

                // Execute procedure
                return _db.OpenSqlDataReader(cmd);
            }

            finally
            {
                cmd.Dispose();
                cmd = null;
            }
        }

        //============================================================================    
        /// <summary>
        /// Executes the passed SqlCommand object and returns a SqlDataReader object
        /// </summary>
        /// <param name="cmd">SqlCommand object to be executed</param>
        /// <returns>SqlDataReader object</returns>
        //============================================================================    
        public SqlDataReader OpenSqlDataReader(SqlCommand cmd)
        {
            try
            {
                // Check for incoming connection
                if (cmd.Connection == null)
                {
                    // Open default connection
                    base.Open();
                    cmd.Connection = base.Connection;
                }

                // Execute command
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }

            catch (System.Data.SqlClient.SqlException exp)
            {
                throw BuildException(exp);
            }
        }

        //==============================================================================
        /// <summary>
        /// Open the connection.
        /// </summary>
        //==============================================================================
        public void Open()
        {
            // open connection
            if (_conn == null)
            {
                _conn = new SqlConnection(_connString);
                _conn.Open();
            }
            else
            {
                if (_conn.State != ConnectionState.Open)
                    _conn.Open();
            }
        }

        //==================================================================================
        /// <summary>
        /// Dispose of the database...
        /// </summary>
        //==================================================================================
        public void Dispose()
        {
            if (_db != null)
            {
                _db.Dispose();
                _db = null;
            }
        }

0
Comment
Question by:cenetadmin
  • 4
  • 2
7 Comments
 
LVL 21

Expert Comment

by:silemone
ID: 22799641
you can close it immediately if you add it to a session variable...

but ideally, you don't need to close your DataReader...you need to close your connection to your Database, but not your datareader...it may cause errors.  Once I tried to dispose of my DataTable at the end of a table after i had finished using it in a finally block and the program gave me major problems on the next go around.
0
 

Author Comment

by:cenetadmin
ID: 22799652
to be more specfic, what code should I comment out, or modify in the code I included?
0
 
LVL 21

Expert Comment

by:silemone
ID: 22799672
oops excuse my earlier comments.  

close it as soon as you've retrieved all data and placed into a table or list.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 21

Expert Comment

by:silemone
ID: 22799713
wow, you've broken your code so far apart...i would suggest debugging...placing a break point to find out when a connection is already opened and not closed before another connection starts...
0
 

Author Comment

by:cenetadmin
ID: 22799745
will not be able to try this until Monday.  Sorry for the delay.
0
 
LVL 21

Accepted Solution

by:
silemone earned 500 total points
ID: 22799799
no problem...enjoy your weekend
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22803935
i will not recommend you to use the kind of design you are going to use and asking the question regarding it.

in my view point instead of returning the data reader object back you should extract the information from it, add it into an objet which can hold that information and then return back that object so that your data reader will be created, used and disposed within the same functions scope so that the garbage collection can be done better instead of the references floating around
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now