SqlCommand.Cancel before SqlDataReader.Close

I’ve just read that you can improve the performance of your SQL queries to Microsoft SQL Servers using .NET 2.0 by simply cancelling the command before closing your data reader.
using (SqlCommand command = connection.CreateCommand())
{
// Your code here
using (SqlDataReader reader = command.ExecuteReader())
{
// Your code here
command.Cancel();
reader.Close();
}
command.Close();
command.Dispose();
}

This is useful if you do not need the return values sending back through the command, and most commonly you will never need to. I’m not sure of the exact performance gain from doing such a modification to your code but I’m certain that since it was mentioned in the MSDN documentation (under remarks), it must be safe to test at least.

About the Author

Sleuth

Hello, I'm Dave! I'm a software developer, and I've lived in Nottingham since October 2005, and I tend to write my random thoughts down here in the hope that they might help or entertain someone in the future. If you have a comment about any of the posts you see on this site, please submit it, as you might also be helping someone!

Leave a Reply

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>