Почему мое приложение зависает при попытке закрыть объект SqlConnection?

Я пытаюсь получить информацию о столбцах на C# из таблицы SQL на SQL Server. Я следую примеру по этой ссылке: http://support.microsoft.com/kb/310107Моя программа странно зависает, когда пытается закрыть соединение. Если соединение не закрыто, программа завершается без каких-либо исключений. Вот мой код:

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.

Помещение SqlConnectionвнутри блока using также приводит к зависанию приложения, если только CommandBehavior.KeyInfoне будет изменено на CommandBehavior.SchemaOnly.

using (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 even here in the using
    DataTable table = reader.GetSchemaTable();
    Console.WriteLine(table.Rows.Count);
}

Рассматриваемая таблица содержит более 3 миллионов строк, но, поскольку я получаю только информацию о схеме, думаю, это не проблема. Мой вопрос: почему мое приложение зависает при попытке закрыть соединение?

РЕШЕНИЕ: Возможно, это не оптимально, но работает; Я вставил оператор command.Cancel();прямо перед вызовом Closeпри подключении:

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.

6
задан Words Like Jared 19 April 2012 в 14:04
поделиться