Skip to content

Unable to connect to SqlServer instance with managed SNI and Timeout=0 on SqlClient 5.0 #1733

@vonzshik

Description

@vonzshik

Describe the bug

While attempting to establish the connection to SqlServer instance while having Timeout=0 in the connection string the app becomes unresponsive. I'm able to reproduce this problem on linux and windows with AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows", true). It works fine on SqlClient 4.1.0.

To reproduce

AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows", true);

var sw = Stopwatch.StartNew();
using var connection = new SqlConnection("Server=.;Database=master;Integrated Security=false;User ID=sa;Password=SomePassword;Pooling=true;Max Pool Size=1024;TrustServerCertificate=true;Timeout=0");
await connection.OpenAsync();

using var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT 1";
await cmd.ExecuteNonQueryAsync();
Console.WriteLine($"Connection established successfully in {sw.ElapsedMilliseconds}ms. Press any key to continue...");
Console.ReadKey();

Expected behavior

SqlClient should be able to establish a connection with Timeout=0, just like in previous verions

Further technical details

Microsoft.Data.SqlClient 5.0
.NET target: .NET 6.0
SQL Server version: SQL Server 2017
Operating system: CentOS 7, Windows 10

Additional context

The problem is because while waiting for the dns, the timeout passed there is the default TimeSpan, which is 0, and that's why it fails immediately (it should have been -1):

TimeSpan ts = default(TimeSpan);
// In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count
// The infinite Timeout is a function of ConnectionString Timeout=0
bool isInfiniteTimeOut = long.MaxValue == timerExpire;
if (!isInfiniteTimeOut)
{
ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
}

This was introduced in #1578.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Regression 💥Issues that are regressions introduced from earlier PRs.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions