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 jus
In your example, you open the reader, read all the rows, and the Cancel the command, but you didn't show where the reader was being closed.
Make sure the canceling happens before the Dispose
/Close
. For example, you wouldn't get a performance boost in this example (real code in production, unfortunately):
using (var rdr = cmd.ExecuteReader (CommandBehavior.Default))
{
retval = DocumentDir.DBRead (rdr);
}
// Optimization. Allows reader to close more quickly.... NOT!
cmd.Cancel (); // bad!
Too bad it's already closed by the Using Statement!
This is how it should read to realize the potential benefit:
using (var rdr = cmd.ExecuteReader (CommandBehavior.Default))
{
retval = DocumentDir.DBRead (rdr);
// Optimization. Allows reader to close more quickly.
cmd.Cancel ();
}
From MSDN SqlCommand.Cancel:
In some, rare, cases, if you call ExecuteReader then call Close (implicitily or explicitly) before calling Cancel, and then call Cancel, the cancel command will not be sent to SQL Server and the result set can continue to stream after you call Close. To avoid this, make sure that you call Cancel before closing the reader or connection.