У меня есть проблема с AggregateException, брошенным из библиотеки .NET. По какой-то причине он не попадает в блок Try-Catch. Это приводит к сбою всего приложения, и в стеке вызовов нет методов из моего кода. Это происходит, когда я проверяю сценарий отключения VPN. Таким образом, я в основном запускаю приложение при подключении к VPN и при запуске приложения я отключаюсь от VPN, а затем исключение брошено, а приложение вылетает, так как оно не пойман. Polly retrypolicy , который находится внутри Parallel.foreach () .
ps. Это не проблема с инструментами> Параметры (или отладка> Опции)> отладка> Общие> Включить только мой код. < /P>
Код: < /p>
await Parallel.ForAsync(0, totalBatchesCount, parallelOptions, async (i, cancellationToken) =>
{
//...
await retryPolicy.ExecuteAsync(async () =>
{
try
{
var batch = await _userRepository.GetBatchAsync(startId, endId);
//...
}
catch (Exception ex)
{
throw new Exception($"Batch failed for startId: {startId} and endId {endId}", ex);
}
});
});
< /code>
Метод репозитория: < /p>
public async Task GetBatchAsync(int startId, int endId)
{
try
{
await using var context = await _contextFactory.CreateDbContextAsync();
return await context.Users
.Where(u => u.UserId >= startId && u.UserId < endId)
.Include(u => u.Invoice)
.AsNoTracking()
.ToListAsync();
}
catch (AggregateException ex)
{
Console.WriteLine(ex.ToString());
throw;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
< /code>
Политика повторной попытки: < /p>
var retryPolicy = Policy
.Handle()
.WaitAndRetryAsync(POLLY_RETRY_COUNT, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(exception, timeSpan, retryCount, context) =>
{
_logger.LogWarning($"Retry {retryCount} due to: {exception.Message}, stack trace: {exception.StackTrace}, inner: {exception?.InnerException?.Message}");
});
< /code>
Исключение: < /p>
Unhandled exception. System.AggregateException: One or more errors occurred. (Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding)
---> MySql.Data.MySqlClient.MySqlException (0x80004005): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding
---> System.TimeoutException: The operation has timed out.
at MySql.Data.Common.StreamCreator.c.b__8_1()
at System.Threading.CancellationTokenSource.Invoke(Delegate d, Object state, CancellationTokenSource source)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
--- End of inner exception stack trace ---
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
at System.Threading.TimerQueueTimer.Fire(Boolean isThreadPool)
at System.Threading.TimerQueue.FireNextTimers()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
Подробнее здесь: https://stackoverflow.com/questions/793 ... not-caught
AggregateException не пойман ⇐ C#
Место общения программистов C#
1738080086
Anonymous
У меня есть проблема с AggregateException, брошенным из библиотеки .NET. По какой-то причине он не попадает в блок Try-Catch. Это приводит к сбою всего приложения, и в стеке вызовов нет методов из моего кода. Это происходит, когда я проверяю сценарий отключения VPN. Таким образом, я в основном запускаю приложение при подключении к VPN и при запуске приложения я отключаюсь от VPN, а затем исключение брошено, а приложение вылетает, так как оно не пойман. Polly retrypolicy , который находится внутри Parallel.foreach () .
ps. Это не проблема с инструментами> Параметры (или отладка> Опции)> отладка> Общие> Включить только мой код. < /P>
Код: < /p>
await Parallel.ForAsync(0, totalBatchesCount, parallelOptions, async (i, cancellationToken) =>
{
//...
await retryPolicy.ExecuteAsync(async () =>
{
try
{
var batch = await _userRepository.GetBatchAsync(startId, endId);
//...
}
catch (Exception ex)
{
throw new Exception($"Batch failed for startId: {startId} and endId {endId}", ex);
}
});
});
< /code>
Метод репозитория: < /p>
public async Task GetBatchAsync(int startId, int endId)
{
try
{
await using var context = await _contextFactory.CreateDbContextAsync();
return await context.Users
.Where(u => u.UserId >= startId && u.UserId < endId)
.Include(u => u.Invoice)
.AsNoTracking()
.ToListAsync();
}
catch (AggregateException ex)
{
Console.WriteLine(ex.ToString());
throw;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
< /code>
Политика повторной попытки: < /p>
var retryPolicy = Policy
.Handle()
.WaitAndRetryAsync(POLLY_RETRY_COUNT, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(exception, timeSpan, retryCount, context) =>
{
_logger.LogWarning($"Retry {retryCount} due to: {exception.Message}, stack trace: {exception.StackTrace}, inner: {exception?.InnerException?.Message}");
});
< /code>
Исключение: < /p>
Unhandled exception. System.AggregateException: One or more errors occurred. (Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding)
---> MySql.Data.MySqlClient.MySqlException (0x80004005): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding
---> System.TimeoutException: The operation has timed out.
at MySql.Data.Common.StreamCreator.c.b__8_1()
at System.Threading.CancellationTokenSource.Invoke(Delegate d, Object state, CancellationTokenSource source)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
--- End of inner exception stack trace ---
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
at System.Threading.TimerQueueTimer.Fire(Boolean isThreadPool)
at System.Threading.TimerQueue.FireNextTimers()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
Подробнее здесь: [url]https://stackoverflow.com/questions/79394458/aggregateexception-is-not-caught[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия