Производный класс MicrosoftSqlAzureExecutionStrategy: количество повторов варьируетсяC#

Место общения программистов C#
Ответить
Anonymous
 Производный класс MicrosoftSqlAzureExecutionStrategy: количество повторов варьируется

Сообщение Anonymous »

Я использую .Net 4.8 и EF6.5 с Microsoft.Data.SqlClient. Я хочу управлять повторными попытками для моего приложения SQL Azure WinForms.
У меня есть класс, производный от MicrosoftSqlAzureExecutionStrategy, для регистрации повторных попыток и добавления дополнительного кода ошибки в целях тестирования. Когда я проверяю свои журналы, там в 3 раза больше записей, чем я ожидал. Когда я удаляю вызов GetNextDelay(..), я даже получаю больше записей в журнале. Как правильно настроить производный класс от MicrosoftSqlAzureExecutionStrategy? Почему количество повторов меняется (я использовал значение по умолчанию, которое должно быть 5)?
Вот мой код:

Код: Выделить всё

public class MyStrategy : MicrosoftSqlAzureExecutionStrategy
{
public static List _exceptionsEncountered = new List();

public MyStrategy(bool reset)
{
if (reset) { _exceptionsEncountered.Clear(); }
}

protected override TimeSpan? GetNextDelay(Exception lastException)
{
return base.GetNextDelay(lastException);
}

protected override bool ShouldRetryOn(Exception exception)
{
_exceptionsEncountered.Add(exception);
var currentRetryCount = _exceptionsEncountered.Count - 1;
var delay = GetNextDelay(exception);
if (delay == null)
{
delay = new TimeSpan(0);
}
int errorCode = -1;
if (exception is Microsoft.Data.SqlClient.SqlException)
{
errorCode = (exception as Microsoft.Data.SqlClient.SqlException).Number;
}
ErrorMessage($"ShouldRetryOn: retry Count: {currentRetryCount}, delay: {delay},  exception no.: {errorCode}, exception: {exception.Message}");

// only for testing:
if (errorCode == 11001) { return true; }

return base.ShouldRetryOn(exception);
}
}

public class DataContextConfiguration : MicrosoftSqlDbConfiguration
{
public DataContextConfiguration()
{
SetProviderFactory(MicrosoftSqlProviderServices.ProviderInvariantName, SqlClientFactory.Instance);
SetProviderServices(MicrosoftSqlProviderServices.ProviderInvariantName, MicrosoftSqlProviderServices.Instance);
/*** set execution/retry strategy of connections** */
SetExecutionStrategy(MicrosoftSqlProviderServices.ProviderInvariantName, () => new MyStrategy(true));
}
}

[DbConfigurationType(typeof(DataContextConfiguration))]
public partial class TestModel : DbContext
{
public TestModel(string connectionString) : base(connectionString)
{
Database.Log = sql => Debug.Write(sql);
//avoid internal errors like Invalid object name 'dbo.__MigrationHistory'.
Database.SetInitializer(null);
}
...
}

//function call:
public string GetIDdata(string myid)
{
try
{
using (var db = new TestModel(ConnectionString))
{
var query = from b in db.testing
where b.id == myid
select b;
if (query.Count() == 0)
{
return String.Empty;
}
else
{
//process data
}
}
}
catch (Exception ex)
{
Helper.ErrorMessage(ex.Message);
return String.Empty;
}
}
Это мой журнал:

Код: Выделить всё

10:46:09.964||Error|ShouldRetryOn: retry Count: 0, delay: 00:00:00,  exception no.: 11001, exception: ...
10:46:40.739||Error|ShouldRetryOn: retry Count: 1, delay: 00:00:03.2390000,  exception no.: 11001, exception: ...
10:47:17.638||Error|ShouldRetryOn: retry Count: 2, delay: 00:00:16.0010000,  exception no.: 11001, exception: ...
10:47:47.356||Error|ShouldRetryOn: retry Count: 0, delay: 00:00:00,  exception no.: 11001, exception: ..
10:48:18.098||Error|ShouldRetryOn: retry Count: 1, delay: 00:00:03.2370000,  exception no.: 11001, exception: ..
10:48:55.303||Error|ShouldRetryOn: retry Count: 2, delay: 00:00:15.8020000,  exception no.: 11001, exception: ..
10:49:25.406||Error|ShouldRetryOn: retry Count: 0, delay: 00:00:00,  exception no.: 11001, exception: ..
10:49:56.162||Error|ShouldRetryOn: retry Count: 0, delay: 00:00:03.0840000,  exception no.: 11001, ..
10:50:33.410||Error|ShouldRetryOn: retry Count: 0, delay: 00:00:15.2000000,  exception no.: 11001, ..
10:50:33.410||Error|Maximum number of retries (5) exceeded while executing database operations with 'MyStrategy'. See inner exception for the most recent failure.
Когда я удаляю вызов GetNextDelay(Exception), мой журнал выглядит следующим образом:

Код: Выделить всё

09:29:58.386||Error|ShouldRetryOn: retry Count: 0,  exception no.: 11001, exception: ...
09:30:28.213||Error|ShouldRetryOn: retry Count: 1,  exception no.: 11001, exception: ...
09:33:05.262||Error|ShouldRetryOn: retry Count: 2,  exception no.: 11001, exception: ...
09:33:38.237||Error|ShouldRetryOn: retry Count: 3,  exception no.: 11001, exception: ...
09:34:15.466||Error|ShouldRetryOn: retry Count: 4,  exception no.: 11001, exception: ...
09:35:01.421||Error|ShouldRetryOn: retry Count: 5,  exception no.: 11001, exception: ...
09:35:31.228||Error|ShouldRetryOn: retry Count: 0,  exception no.: 11001, exception: ...
09:36:01.022||Error|ShouldRetryOn: retry Count: 1,  exception no.: 11001, exception: ...
09:36:31.878||Error|ShouldRetryOn: retry Count: 2,  exception no.: 11001, exception: ...
09:37:04.808||Error|ShouldRetryOn: retry Count: 3,  exception no.: 11001, exception: ...
09:37:41.787||Error|ShouldRetryOn: retry Count: 4,  exception no.: 11001, exception: ...
09:38:27.710||Error|ShouldRetryOn: retry Count: 5,  exception no.: 11001, exception: ...
09:38:57.994||Error|ShouldRetryOn: retry Count: 0,  exception no.: 11001, exception: ...
09:39:27.795||Error|ShouldRetryOn: retry Count: 0,  exception no.: 11001, exception: ...
09:39:58.711||Error|ShouldRetryOn: retry Count: 0,  exception no.: 11001, exception: ...
09:40:31.726||Error|ShouldRetryOn: retry Count: 0,  exception no.: 11001, exception: ...
09:41:09.101||Error|ShouldRetryOn: retry Count: 0,  exception no.: 11001, exception: ...
09:41:55.337||Error|ShouldRetryOn: retry Count: 0,  exception no.: 11001, exception: ...
Есть ли у кого-нибудь объяснение этому? Разве не должно быть только 5 повторных попыток?

Подробнее здесь: https://stackoverflow.com/questions/790 ... ber-varies
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»