Skip to content

ReadAsync CanellationTokenSource performance problem #2408

Open

Description

@TomislavBaljint

Describe the bug

Reading data from a table in parallel with multiple SqlDataReaders (each reading their part of a table).
When a reader is iterated with a cancellation token created from CanellationTokenSource there is a significant performance drop.

Difference in performance:
image

cancellation = CancellationToken.None; 
cancellation = new CancellationToken();
cancellation = new CancellationTokenSource().Token;
while (await reader.ReadAsync(cancellation).ConfigureAwait(false)) { }

To reproduce

Create the table in a MS SqlServer database.
Use the TABLE_CREATE_SQL script from the code to create a 50M record table with around 1.7GB of data.
Change the connection data in the code to your database.
Run the benchmark.

    <PackageReference Include="BenchmarkDotNet" Version="0.13.12" />
    <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
using BenchmarkDotNet.Attributes;
using Microsoft.Data.SqlClient;

namespace SqlReadAsync;

[SimpleJob(1, 1, 1, 1, "1", false)]
public class Benchmarks
{
	private const string SERVER = "server";
	private const string DATABASE = "db";
	private const string USER = "user";
	private const string PASSWORD = "pass";
	private const string CONNECTION_STRING = $"Data Source={SERVER};Initial Catalog={DATABASE};User ID={USER};Password={PASSWORD};Trust Server Certificate=True;Pooling=False;";
	
	#region TABLE SQL

	private const string TABLE_CREATE_SQL = """
		DROP TABLE IF EXISTS dbo.test_table;
		WITH t1(n) AS
			(
				SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL
					UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT NULL
			)
			, t2(n) AS
		(
			SELECT NULL FROM t1 AS t1, t1 AS t2, t1 AS t3, t1 AS t4, t1 AS t5, t1 AS t6, t1 AS t7, t1 AS t8, t1 AS t9
		)
		, t3(n) AS
		(
			SELECT TOP 50000000 ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM t2
		)
		SELECT
			ID = ISNULL(t.n, 0),
			c1 = CAST(t.n AS VARCHAR(12)),
			d1 = DATEADD(MINUTE, t.n, '1970-01-01')
		INTO dbo.test_table FROM t3 AS t;
		ALTER TABLE dbo.test_table ADD CONSTRAINT PK_test_table PRIMARY KEY(ID);
		""";

	#endregion

	private const string SELECT_PART = "SELECT ID, c1, d1 FROM dbo.test_table";
	private readonly string[] whereParts =
	[
		" WHERE ID > 0 AND ID <= 10000000",
		" WHERE ID > 10000000 AND ID <= 20000000",
		" WHERE ID > 20000000 AND ID <= 30000000",
		" WHERE ID > 30000000 AND ID <= 40000000",
		" WHERE ID > 40000000 AND ID <= 50000000",
	];

	public enum ReadType
	{
		Sync,
		Async,
		AsyncToken,
		AsyncTokenSource,
	}

	[Params(ReadType.Sync, ReadType.Async, ReadType.AsyncToken, ReadType.AsyncTokenSource)]
	public ReadType Type { get; set; }
	
	private static Task ReadSync(string? whereClause)
	{
		using var conn = new SqlConnection(CONNECTION_STRING);
		using var cmd = new SqlCommand($"{SELECT_PART}{whereClause}", conn);
		conn.Open();
		using SqlDataReader reader = cmd.ExecuteReader();

		while (reader.Read()) { }

		return Task.CompletedTask;
	}

	private static async Task ReadAsync(string whereClause, CancellationToken cancellation)
	{
		using var conn = new SqlConnection(CONNECTION_STRING);
		using var cmd = new SqlCommand($"{SELECT_PART}{whereClause}", conn) { CommandTimeout = 0 };
		conn.Open();
		using SqlDataReader reader = cmd.ExecuteReader();

		while (await reader.ReadAsync(cancellation).ConfigureAwait(false)) { }
	}

	[Benchmark]
	public async Task TestRead()
	{
		CancellationToken cancellation = CancellationToken.None;
		switch (Type)
		{
			case ReadType.Sync:
			case ReadType.Async:
				cancellation = CancellationToken.None;
				break;
			case ReadType.AsyncToken:
				cancellation = new CancellationToken();
				break;
			case ReadType.AsyncTokenSource:
				cancellation = new CancellationTokenSource().Token;
				break;
		}

		var tasks = new List<Task>();
		foreach (string wherePart in whereParts)
		{
			switch (Type)
			{
				case ReadType.Sync:
					tasks.Add(Task.Run(() => ReadSync(wherePart)));
					break;
				case ReadType.Async:
					tasks.Add(Task.Run(() => ReadAsync(wherePart, cancellation)));
					break;
				case ReadType.AsyncToken:
					tasks.Add(Task.Run(() => ReadAsync(wherePart, cancellation)));
					break;
				case ReadType.AsyncTokenSource:
					tasks.Add(Task.Run(() => ReadAsync(wherePart, cancellation)));
					break;
			}
		}
		await Task.WhenAll(tasks);
	}
}

Expected behavior

Similar performance between runs.

Further technical details

Microsoft.Data.SqlClient version: 5.2.0
.NET target: net8.0
SQL Server version: SQL Server 2019
SQL Server docker: mcr.microsoft.com/mssql/server:2019-latest
Operating system: Windows 11, Docker container

Additional context
Problem was found on Microsoft.Data.SqlClient version 5.1.4, but still present.

Activity

  1. Wraith2 commented on Mar 19, 2024

    @Wraith2
    Contributor

    The performance difference is caused by registration and unregistration of a cancellation event handler in ReadAsync and cannot be avoided if you want to use a cancellation token which is provided by a CancellationTokenSource.

  2. Douglasproglima commented on Oct 11, 2024

    @Douglasproglima
  3. Wraith2 commented on Oct 11, 2024

    @Wraith2
    Contributor

    Can you give context to your comment please?
    I'm not sure why this is still open. The performance difference is explained and unavoidable, unfortunately.

  4. roji commented on Oct 11, 2024

    @roji
    Member

    @Wraith2 are you saying that the almost 4 second difference is just a result of registering/unregistering the event handler?

  5. vonzshik commented on Oct 11, 2024

    @vonzshik

    @roji that's the result of registering/unregistering the event handler 50 million times distributed over 5 concurrent threads. For example, locally with this repro I see the difference between 1400 ms (if CancellationToken is passed) and 11ms (if it's not).

    using System.Diagnostics;
    
    while (true)
    {
        using var cts = new CancellationTokenSource();
        var sw = Stopwatch.StartNew();
    
        var tasks = new List<Task>();
    
        for (var i = 0; i < 5; i++)
        {
            tasks.Add(Task.Run(() => Callback(cts.Token)));
        }
        await Task.WhenAll(tasks);
    
        Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}ms");
    }
    
    void Callback(CancellationToken cancellationToken)
    {
        for (var i = 0; i < 10_000_000; i++)
        {
            using var _ = cancellationToken.Register(() =>
            {
                
            });
        }
    }
  6. roji commented on Oct 11, 2024

    @roji
    Member

    I see, thanks @vonzshik!

  7. Wraith2 commented on Oct 11, 2024

    @Wraith2
    Contributor

    @Wraith2 are you saying that the almost 4 second difference is just a result of registering/unregistering the event handler?

    Yup, I profiled it. Slightly surprising but it's all down to the registration of the callback and administering it.

  8. moved this from To triage to Backlog in SqlClient Boardon Jan 8, 2026
  9. added
    Performance 📈
    on Jan 8, 2026
  10. added
    Performance 📈
    and removed
    Performance 📈
    on Jun 10, 2026
  11. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  12. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation
    Area Area\Async
    Duplicates Potentially related: #593
    Regression Not indicated (reporter confirms same behavior on 5.1.4 and 5.2.0 — long-standing, not a regression)

    Analysis

    This issue reports a significant throughput drop when SqlDataReader.ReadAsync is called with a CancellationToken sourced from a CancellationTokenSource (vs. CancellationToken.None/default), under high-iteration parallel reads. Maintainers (@Wraith2, @vonzshik) have already root-caused this: the overhead is inherent to .NET's CancellationToken.Register/unregister cost when repeated millions of times (confirmed via profiling and a minimal repro unrelated to SqlClient's TDS/network code). This is largely an upstream cost of the cancellation registration mechanism rather than a SqlClient-specific defect, though SqlClient's async read path could potentially reduce the frequency of registration (e.g., batching registration across multiple ReadAsync calls or reusing linked token registrations) to mitigate the impact. Severity: P3 (known, explained, workaround exists — avoid passing a live token when cancellation isn't needed).

    Next Steps

    • Review Reading large data (binary, text) asynchronously is extremely slow #593 for overlapping discussion/root cause before further action — the two issues may warrant consolidation.
    • If further mitigation is desired, assign to Copilot coding agent to investigate whether TdsParserStateObject/SqlDataReader's async read path can reduce CancellationToken.Register call frequency (e.g., caching/reusing a single registration per command execution instead of per ReadAsync call), and to add a benchmark regression test under PerformanceTests/ to track this overhead going forward.
    • Since maintainers already consider the root cause explained and not directly fixable at the SqlClient level, consider whether this should be re-labeled/closed as "by design" pending any mitigation decision, or kept open as a tracked performance optimization opportunity.

    Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.

    Generated by SqlClient Issue Auto-Triage for #2408 · copilot · auto · 55.9 AIC · ⌖ 14.7 AIC · ⊞ 11.9K · ◷

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area\AsyncPerformance 📈

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions