SQL ServerのSQLテーブルからC#で列情報を取得しようとしています。私はこのリンクの例に従っています:http://support.microsoft.com/kb/310107私のプログラムは接続を閉じようとすると不思議にハングアップします。接続が閉じられていない場合、プログラムは例外なしで終了します。またCommandBehavior.KeyInfo
がCommandBehavior.SchemaOnly
に変更されない限り、アプリケーションがハングアップしSqlConnectionオブジェクトを閉じるときにアプリケーションがハングするのはなぜですか?
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 (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);
}
問題のテーブルには、300万行を持っているが、私は唯一のスキーマ情報を取得しておりますので、私はこれは問題ではないと思うだろう。私の質問です:接続を閉じようとしているときに私のアプリケーションが立ち往生しないのはなぜですか?
解決策:これは最適ではないかもしれませんが、動作します。私はClose
は、接続で呼び出される直前command.Cancel();
文を挿入:
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.
クローズ処理を長くする可能性のある他の変数を設定しているかどうかを確認するために、接続文字列(重要な情報のlilkeユーザー名、パスワード、サーバー、データベースは除きます)を共有できますか。 –
確かに。 @ " データソース= ****; 初期カタログ= ****; ユーザーID = ****; パスワード= ****; 接続タイムアウト= 60;" –
最初に読者を閉じてはいけませんか? – Deb