SqlCommand.Cancel() causes a performance boost?

前端 未结 4 785
感情败类
感情败类 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:46

    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!

提交回复
热议问题