Solved

When to close my datareader

Posted on 2008-10-24
7
1,108 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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
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

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

895 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

16 Experts available now in Live!

Get 1:1 Help Now