SqlCommand.Cancel() causes a performance boost?

前端 未结 4 789
感情败类
感情败类 2021-02-08 02:21

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

4条回答
  •  花落未央
    2021-02-08 02:40

    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.

提交回复
热议问题