Solved

When to close my datareader

Posted on 2008-10-24
7
1,120 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 our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

 
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
parsing JSON help 1 20
The control parameters are not inputing the value when displaying in a report viewer 13 26
Change to file doesn't show up 16 51
asp.net mvc 2 21
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

839 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