Open TomislavBaljint opened 8 months ago
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.
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.
@Wraith2 are you saying that the almost 4 second difference is just a result of registering/unregistering the event handler?
@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(() =>
{
});
}
}
I see, thanks @vonzshik!
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:
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.
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.