Solved

When to close my datareader

Posted on 2008-10-24
7
1,130 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ASP.NET Complete Life Cycle for all the controls 2 43
Web page design problem 3 41
Shared Service Environment 2 54
Difference between Leaflet and MapBox? 5 45
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

734 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