Skip to content

Don't cancel the command after QueryUnbufferedAsync completes normally - #2245

Merged
mgravell merged 1 commit into
DapperLib:mainfrom
aaronwilliams-tesouro:fix/queryunbufferedasync-cancel-after-read
Nov 20, 2026
Merged

mgravell merged 1 commit into
DapperLib:mainfrom
aaronwilliams-tesouro:fix/queryunbufferedasync-cancel-after-read

Conversation

@aaronwilliams-tesouro

Copy link
Copy Markdown
Contributor

Fixes #2188.

Problem

QueryUnbufferedAsync calls DbCommand.Cancel() in its finally whenever !reader.IsClosed. On the success path the reader is still open at that point, so every query that is read to the end gets cancelled. Npgsql sends that cancel over a new connection, so each completed query costs an extra connection, plus server work to cancel a command that has already finished. #2188 reports similar behaviour with MySqlConnector.

Fix

Close the reader and set it to null before the finally runs. The read-to-end exit now mirrors the sync QueryImpl and QueryRowImpl, comment included. The early exit for statements that return no columns gets the same treatment. Sync QueryImpl still cancels on that exit and could get the same fix in a follow-up. Cancel() still runs when the caller stops enumerating early or an exception is thrown, which is the case #2121 added it for.

command.OnCompleted() now runs after the reader is closed, as it does on the sync path. Providers fill in output parameters once the reader closes, so they're now populated when that callback runs.

#2207 tried a drained flag and was closed by its author without review. This PR mirrors the sync code instead and adds tests.

Tests

The tests use SQLite: it needs no server and still reproduces the bug. They count Cancel() calls through a pass-through DbConnection/DbCommand wrapper:

Test Before After
QueryUnbufferedAsync_ReadToEnd_DoesNotCancel fails: 1 cancel passes: 0
QueryUnbufferedAsync_NoColumns_DoesNotCancel fails: 1 cancel passes: 0
QueryUnbufferedAsync_StopEarly_Cancels passes: 1 passes: 1

Related: #2220 removes Cancel() from the sync single-row cleanup.

I agree to the terms in NonCLA.md.

QueryUnbufferedAsync's finally block calls DbCommand.Cancel() whenever the
reader is still open, and on the success path it always is. Npgsql sends
that cancel over a new connection, so every completed query pays for an
extra connection to cancel a command that has already finished.

Close the reader and clear it after reading to the end, as the sync Query
and QueryRow paths already do. Do the same on the early exit for statements
with no columns; sync QueryImpl still cancels there. Cancel() now only runs
when the caller stops early or an error is thrown.

Fixes DapperLib#2188
@aaronwilliams-tesouro
aaronwilliams-tesouro marked this pull request as ready for review October 20, 2026 16:32
@mgravell
mgravell merged commit 5db1de6 into DapperLib:main Nov 20, 2026
@mgravell

Copy link
Copy Markdown
Member

Verified against real servers and merged (via a merge commit, since #2242 landed moments earlier and touched the same test file). Nice work — mirroring the sync happy-path dispose keeps the cancel exactly where it belongs, for abandoned readers only, and the cancel-counting test harness is a keeper. This resolves the Npgsql regression in #2188. Thanks!

This was referenced Nov 20, 2026
mvmorten added a commit to mvmorten/dashboard-starter that referenced this pull request Nov 23, 2026
Updated [Dapper](https://github.com/DapperLib/Dapper) from 2.1.89 to
2.1.100.

<details>
<summary>Release notes</summary>

_Sourced from [Dapper's
releases](https://github.com/DapperLib/Dapper/releases)._

## 2.1.100

## What's Changed
* Fix 2.1.86 unbox-gate regressions: array columns to interface members,
sql_variant to primitives by @​mgravell in
DapperLib/Dapper#2271
* Fix command disposal, parameter callbacks, handler-cache staleness,
static properties, and type-map races by @​mgravell in
DapperLib/Dapper#2272
* Fix deserializer cache race by @​jnm2 in
DapperLib/Dapper#2219
* Fix cache corruption due to CollectCacheGarbage call during
GridReader/Async queries by @​aklein53 in
DapperLib/Dapper#2218
* Fix false cache hit accounting on initial MultiMapAsync execution by
@​Nacl-HCl in DapperLib/Dapper#2242
* Fixes QueryMultiple corrupting a later Query<T>'s DynamicParameters --
fixes #​243, #​2091 by @​NadeemAfana in
DapperLib/Dapper#2214
* Don't cancel the command after QueryUnbufferedAsync completes normally
by @​aaronwilliams-tesouro in
DapperLib/Dapper#2245
* Preserve Size set by type handlers for string parameters by
@​JiuYue0820 in DapperLib/Dapper#2221
* Fix MultiMapAsync disposing the reader before unbuffered results are
enumerated by @​jinseojang0903 in
DapperLib/Dapper#2229
* Stop boxing values read via GetFieldValue<T> for the error message by
@​Giorgi in DapperLib/Dapper#2265
* Fix list initializer in bulk Execute README example by @​dajiaohuang
in DapperLib/Dapper#2243

## New Contributors
* @​aklein53 made their first contribution in
DapperLib/Dapper#2218
* @​Nacl-HCl made their first contribution in
DapperLib/Dapper#2242
* @​NadeemAfana made their first contribution in
DapperLib/Dapper#2214
* @​aaronwilliams-tesouro made their first contribution in
DapperLib/Dapper#2245
* @​JiuYue0820 made their first contribution in
DapperLib/Dapper#2221
* @​jinseojang0903 made their first contribution in
DapperLib/Dapper#2229
* @​dajiaohuang made their first contribution in
DapperLib/Dapper#2243

**Full Changelog**:
DapperLib/Dapper@2.1.89...2.1.100

Commits viewable in [compare
view](DapperLib/Dapper@2.1.89...2.1.100).
</details>

[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=Dapper&package-manager=nuget&previous-version=2.1.89&new-version=2.1.100)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Michael Mortensen <mvmorten@users.noreply.github.com>
This was referenced Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

QueryUnbufferedAsync cancels command unnecessarily for Npgsql, causing performance degradation

2 participants