private SqlConnection OpenConnection()
{
// Needed for retries;
Random rand = null;
for (int i = 1;; i++)
{
try
{
var connection = new SqlConnection(_connectionString);
var task = connection.OpenAsync();
task.Wait(_cancelToken.Token);
connection.Disposed += Connection_Disposed;
lock(SyncRoot)
{
_connectionCounter++;
if (SqlServerSettings.Default.ConnectionPoolUsageWarningLevel<=0)
{
Platform.Log(LogLevel.Warn, "# Max SqlConnection Pool Size={0}, current Db Connections={1}",
_maxPoolSize, _connectionCounter);
}
else if (_connectionCounter > _maxPoolSize / SqlServerSettings.Default.ConnectionPoolUsageWarningLevel)
{
if (_connectionCounter%3==0)
{
Platform.Log(LogLevel.Warn, "# Max SqlConnection Pool Size={0}, current Db Connections={1}",
_maxPoolSize, _connectionCounter);
}
}
}
return connection;
}
catch (SqlException e)
{
// The connection failed. Check the Sql error class 0x14 is for connection failure, let the
// other error types through.
if ((i >= 10) || e.Class != 0x14 || _cancelToken.IsCancellationRequested)
throw;
if (rand == null) rand = new Random();
// Sleep a random amount between 5 and 10 seconds
int sleepTime = rand.Next(5 * 1000, 10 * 1000);
Platform.Log(LogLevel.Warn,
"Failure connecting to the database, sleeping {0} milliseconds and retrying", sleepTime);
if (_cancelToken.IsCancellationRequested)
throw;
}
catch (AggregateException e)
{
var x = e.InnerException as SqlException;
if (x != null)
{
// The connection failed. Check the Sql error class 0x14 is for connection failure, let the
// other error types through.
if ((i >= 10) || x.Class != 0x14 || _cancelToken.IsCancellationRequested)
throw;
if (rand == null) rand = new Random();
// Sleep a random amount between 5 and 10 seconds
int sleepTime = rand.Next(5 * 1000, 10 * 1000);
Platform.Log(LogLevel.Warn,
"Failure connecting to the database, sleeping {0} milliseconds and retrying", sleepTime);
if (_cancelToken.IsCancellationRequested)
throw;
}
else
throw;
}
}
}