I am trying to get column information in C # from a SQL table on SQL Server. I follow the example in this link: http://support.microsoft.com/kb/310107 My program hangs strangely when I try to close the connection. If the connection is not closed, the program exits without any exceptions. Here is my code:
SqlConnection connection = new SqlConnection(@"MyConnectionString"); connection.Open(); SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection); SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast. DataTable table = reader.GetSchemaTable(); Console.WriteLine(table.Rows.Count); connection.Close(); // Alternatively If this line is commented out, the program runs fast.
Entering SqlConnection
inside the used block also causes the application to freeze if CommandBehavior.KeyInfo
not changed to CommandBehavior.SchemaOnly
.
using (SqlConnection connection = new SqlConnection(@"MyConnectionString")) { connection.Open(); SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection); SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo);
There are more than 3 million rows in the table in question, but since I only get information about the scheme, I think this will not be a problem. My question is: why does my application get stuck when trying to close the connection?
SOLUTION This may not be optimal, but it works; I inserted the instruction command.Cancel();
just before calling Close
in the connection:
SqlConnection connection = new SqlConnection(@"MyConnectionString"); connection.Open(); SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection); SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast. DataTable table = reader.GetSchemaTable(); Console.WriteLine(table.Rows.Count); command.Cancel(); // <-- This is it. connection.Close(); // Alternatively If this line is commented out, the program runs fast.
source share