Cancelling `SqlBatch.ExecuteNonQueryAsync` throws `ArgumentOutOfRangeException` from `SqlCommand.GetBatchCommand` instead of a cancellation exception

Aperta
#5,042 1 commento 0 reazioni 1 assegnatario Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@cheenamalhotra ci sta già lavorando.

Dal 13/11/2026.

  • #5058 di @cheenamalhotra — aperta

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
53/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
csharp, sql
Ambito
databases

Direzione di ricerca

Start with TdsParser.ThrowExceptionAndWarning and SqlCommand.GetBatchCommand, then trace how GetCurrentBatchIndex is used in TdsParser.TryRun and how both exception branches retrieve a batch command. Check how valid indices are defined in batch and non-batch mode. Done means cancellation and other errors at the end of a batch no longer become ArgumentOutOfRangeException; use the supplied LocalDB reproduction to verify.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Describe the bug

When the CancellationToken passed to SqlBatch.ExecuteNonQueryAsync fires just after the last batch command finished, ArgumentOutOfRangeException is thrown from inside SqlClient instead of the expected cancellation exception (SqlException "Operation cancelled by user" / OperationCanceledException).

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at Microsoft.Data.SqlClient.SqlCommand.GetBatchCommand(Int32 index)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, SqlCommand command, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
   at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
   at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)

We hit this in production in an ASP.NET Core endpoint that runs a single-command SqlBatch with HttpContext.RequestAborted: when the client goes away, the request fails with this exception rather than a cancellation, and the real cause is hidden.

Analysis
  1. Every DONEPROC increments SqlCommand._currentlyExecutingBatch (SqlCommand.OnDoneProc). After the last command's DONEPROC it equals _RPCList.Count.
  2. If the attention ACK is processed after that, TdsParser.TryRun adds the "Operation cancelled by user" error with batchIndex: cmdHandler?.GetCurrentBatchIndex(), which is now _RPCList.Count.
  3. ThrowExceptionAndWarning then calls command.GetBatchCommand(index) → _RPCList[_RPCList.Count] → ArgumentOutOfRangeException, which replaces the cancellation error.

The same applies to any error added with GetCurrentBatchIndex() after the last DONEPROC (e.g. the SevereError paths in TryRun).

A related spot: the temp.Count == 1 && temp[0].Exception != null branch calls command?.GetBatchCommand(temp[0].BatchIndex) without the >= 0 check the other branch has, so a BatchIndex of -1 (non-batch mode) would throw the same way.

Possible fix: check the index against _RPCList.Count (e.g. have GetBatchCommand return null for an index outside the list), and use the same guard in both branches of ThrowExceptionAndWarning.

To reproduce

LocalDB, .NET 10, Microsoft.Data.SqlClient 7.1.1. It fails in about 40% of iterations:

using Microsoft.Data.SqlClient;

const string cs = @"Server=(localdb)\MSSQLLocalDB;Database=tempdb;Integrated Security=true;Encrypt=false";
await using (var c = new SqlConnection(cs))
{
    await c.OpenAsync();
    await using var setup = new SqlCommand("IF OBJECT_ID('dbo.ReproItems') IS NULL CREATE TABLE dbo.ReproItems (Id int NOT NULL)", c);
    await setup.ExecuteNonQueryAsync();
}

int aoore = 0, other = 0;
for (var i = 0; i < 20000; i++)
{
    await using var conn = new SqlConnection(cs);
    await conn.OpenAsync();
    await using var batch = new SqlBatch(conn);
    var cmd = new SqlBatchCommand("DELETE FROM dbo.ReproItems WHERE Id = @id");
    cmd.Parameters.AddWithValue("@id", i);
    batch.BatchCommands.Add(cmd);

    using var cts = new CancellationTokenSource();
    var spin = i % 400; // vary the moment the cancellation hits
    var cancelTask = Task.Run(() => { Thread.SpinWait(spin * 20); cts.Cancel(); });
    try { await batch.ExecuteNonQueryAsync(cts.Token); }
    catch (ArgumentOutOfRangeException ex) { if (aoore++ == 0) Console.WriteLine(ex); }
    catch { other++; }
    await cancelTask;
}
Console.WriteLine($"ArgumentOutOfRangeException: {aoore}, other exceptions: {other}");

Result of one run: 6204 completed, 4429 cancelled as expected, 8925 ArgumentOutOfRangeException.

Expected behavior

A cancellation exception (as SqlCommand.ExecuteNonQueryAsync throws), never ArgumentOutOfRangeException.

Further technical details
  • Microsoft.Data.SqlClient 7.1.1. The code is unchanged on main (TdsParser.ThrowExceptionAndWarning, SqlCommand.GetBatchCommand / GetCurrentBatchIndex).
  • .NET 10, Windows 11, SQL Server Express LocalDB.
Lingua principale
C#
Stelle
1k
Fork
352
Merge medio
2g 18h
PR unite (30g)
133

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di dotnet/SqlClient

Tutte le issue di dotnet/SqlClient

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.