Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Probable leak while using SqlDataReader in ADO.NET

0.00/5 (No votes)
14 Apr 2011CPOL 12.9K  
If you want to be sure that every object is closed, I would use this method: while (true){ Thread.Sleep(2000); using (SqlConnection objConnection = new SqlConnection(@Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=.;Max Pool Size=1))...
If you want to be sure that every object is closed, I would use this method:

C#
while (true)
{
    Thread.Sleep(2000);
    using (SqlConnection objConnection = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=.;Max Pool Size=1"))
    using (SqlCommand objCommand = new SqlCommand("Select * from customers", objConnection))
    {
        objConnection.Open();

        using (SqlDataReader reader = objCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
        {
            while (reader.Read())
            {
            }
            Console.WriteLine((i++).ToString());
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)