I have seen this show up several places in code, never with an explanation, just a cryptic comment above it (Declaration and execution included for an idea of context. It's just a standard procedure of running a SqlCommand):
//SqlCommand cmd = new SqlCommand();
//cmd.ExecuteReader();
//Read off the results
//Cancel the command. This improves query time.
cmd.Cancel ();
Basically, after finishing a query, it goes back and cancels it, claiming some performance boost. I suppose you might get some memory back when it goes and frees up the XmlReader, but usually it's about to go out of scope anyways.
I've never bothered with it before, but it's finally showed up in some code I'm reviewing. Does canceling a SqlCommand after running it in the code actually somehow speed it up, or is this just some weird programmer superstition?
Calling Cancel
gives a potentially MASSIVE performance improvement if your call to ExecuteReader
returns a large number of rows, and you don't read all the rows.
To illustrate, let's say a query returns a million rows, and you close the reader after reading just the first 1000 rows. If you fail to call Cancel
before closing the reader, the Close
method will block while it internally enumerates through the remaining 999,000 rows
Try it and see!
According to MSDN, this is correct.
The Close method fills in the values for output parameters, return values and RecordsAffected, increasing the time that it takes to close a SqlDataReader that was used to process a large or complex query. When the return values and the number of records affected by a query are not significant, the time that it takes to close the SqlDataReader can be reduced by calling the Cancel method of the associated SqlCommand object before calling the Close method.
Weird!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With