Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/ corefx Public archive

SqlConnection timeout test is ported #26306

Merged
merged 1 commit into from
Jan 16, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.


using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using Xunit;

namespace System.Data.SqlClient.Tests
Expand Down Expand Up @@ -79,5 +81,97 @@ public void SqlConnectionInvalidParameters()
Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout=1a;"));
Assert.Throws<ArgumentException>(() => new SqlConnection("Integrated Security=truee"));
}

[Fact]
public void ConnectionTimeoutTestWithThread()
{
int timeoutSec = 5;
string connStrNotAvailable = $"Server=tcp:fakeServer,1433;uid=fakeuser;pwd=fakepwd;Connection Timeout={timeoutSec}";

List<ConnectionWorker> list = new List<ConnectionWorker>();
for (int i = 0; i < 10; ++i)
{
list.Add(new ConnectionWorker(connStrNotAvailable));
}

ConnectionWorker.Start();
ConnectionWorker.Stop();

double theMax = 0;
foreach (ConnectionWorker w in list)
{
if (theMax < w.MaxTimeElapsed)
{
theMax = w.MaxTimeElapsed;
}
}

int threshold = (timeoutSec + 1) * 1000;
Assert.True(theMax < threshold);
}

public class ConnectionWorker
{
private static ManualResetEventSlim startEvent = new ManualResetEventSlim(false);
private static List<ConnectionWorker> workerList = new List<ConnectionWorker>();
private ManualResetEventSlim doneEvent = new ManualResetEventSlim(false);
private double maxTimeElapsed;
private Thread thread;
private string connectionString;

public ConnectionWorker(string connectionString)
{
workerList.Add(this);
this.connectionString = connectionString;
thread = new Thread(new ThreadStart(SqlConnectionOpen));
thread.Start();
}

public double MaxTimeElapsed
{
get
{
return maxTimeElapsed;
}
}

public static void Start()
{
startEvent.Set();
}

public static void Stop()
{
foreach (ConnectionWorker w in workerList)
{
w.doneEvent.Wait();
}
}

public void SqlConnectionOpen()
{
startEvent.Wait();

Stopwatch sw = new Stopwatch();
using (SqlConnection con = new SqlConnection(connectionString))
{
sw.Start();
try
{
con.Open();
}
catch { }
sw.Stop();
}

double elapsed = sw.Elapsed.TotalMilliseconds;
if (maxTimeElapsed < elapsed)
{
maxTimeElapsed = elapsed;
}

doneEvent.Set();
}
}
}
}