I'm attempting to use the CancellationToken with SqlConnection.OpenAsync() to limit the amount of time that the OpenAsync function takes.
I create a new CancellationToken and set it to cancel after say 200 milliseconds. I then pass it to OpenAsync(token). However this function still can take a few seconds to run.
Looking at the documentation I cant really see what I'm doing wrong. https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.openasync?view=netframework-4.7.2
Here is the code I'm using:
private async void btnTestConnection_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(SQLConnectionString);
Task.Run(() => QuickConnectionTest(connection)).Wait();
}
public async Task QuickConnectionTest(SqlConnection connection)
{
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
source.CancelAfter(200);
ConnectionOK = false;
try
{
using (connection)
{
await connection.OpenAsync(token);
if (connection.State == System.Data.ConnectionState.Open)
{
ConnectionOK = true;
}
}
}
catch (Exception ex)
{
ErrorMessage = ex.ToString();
}
}
I was expecting OpenAsync() to end early when the CancellationToken to throw a OperationCanceledException when 200ms had passed but it just waits.
To replicate this I do the following: